Search code examples
pythondjangoauthenticationdjango-viewsseparation-of-concerns

Django - Separation of concerns and authentication


I tried to separate the authentication of view (controller). In my view the code did not seem to be in a good place. Then I came to the result shown in the code below. This is wrong, I can improve even more, or worry about this is silly?

views.py

def sign_in(request):
    form = SignInForm(request.POST or None)
    if form.is_valid():
        login(request, form.user)
        return redirect('user/home/')
    context = {'sign_in_form' : form}
    context.update(csrf(request))
    return render_to_response('app_user/sign_in.html', context)

forms.py

class SignInForm(forms.Form):
username = forms.CharField(required=True, max_length=30, label='Username')
password = forms.CharField(widget=forms.PasswordInput, max_length=30, label='Password')

user = None

def clean(self):
    data = self.cleaned_data
    if super(SignInForm, self).is_valid():
        user = authenticate(username=data.get('username'),password=data.get('password'))
        if user is None:
            raise forms.ValidationError("Wrong user or password")
        if not user.is_active:
            raise forms.ValidationError("User is disabled")
        self.user = user
    return data

Solution

  • I dont understand whats wrong with your code. why do you say its wrong ?

    Other then that,why dont you prefer to use the Auth login form ? Look at AuthenticationForm in the Auth module, Its done exactly what you are trying to do.

    Also , you should consider to pass a Request Context in your view , this way you will not have to pass the csrf manually.