Last active
September 1, 2015 11:25
-
-
Save eugena/738425a1a65fcd11116c to your computer and use it in GitHub Desktop.
Form mixins for django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponseRedirect | |
from django.contrib.auth.decorators import login_required | |
class LoginRequiredMixin(object): | |
""" | |
LoginRequired Mixin | |
""" | |
@classmethod | |
def as_view(cls, **initkwargs): | |
view = super(LoginRequiredMixin, cls).as_view(**initkwargs) | |
return login_required(view) | |
class SameSuccessUrlMixin(object): | |
""" | |
A mixin for form view with the same success url | |
""" | |
def get_success_url(self): | |
""" | |
Returns the supplied URL. | |
""" | |
return self.request.get_full_path() | |
class GetSessionUserAsEditingObjectMixin(object): | |
""" | |
A mixin which mixes the function get_object and | |
returns user according to session user_id as the result. | |
""" | |
def get_object(self, queryset=None): | |
""" | |
Returns the object the view is displaying. | |
""" | |
return self.model.objects.get(pk=self.request.session.get('user_id')) | |
class GetUserAsEditingObjectMixin(object): | |
""" | |
A mixin which mixes the function get_object and | |
returns current user (Client) as the result. | |
""" | |
def get_object(self, queryset=None): | |
""" | |
Returns the object the view is displaying. | |
""" | |
return self.model.objects.get(pk=self.request.user.id) | |
class RedirectIfAuthenticatedMixin(object): | |
""" | |
A mixin which returns HttpResponseRedirect to form success url | |
if user is authenticated and response of parent's get otherwise | |
""" | |
def get(self, request, *args, **kwargs): | |
""" | |
Handles GET requests and instantiates a blank version of the form. | |
""" | |
if self.request.user.is_authenticated(): | |
response = HttpResponseRedirect(self.get_success_url()) | |
else: | |
response = super(RedirectIfAuthenticatedMixin, self).get(request, *args, **kwargs) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment