1

I'm trying to build a login system with the Django framework. I extended the UserCreationForm to add names and emails. Now that I have users in the database, I'm trying to authenticate them and log them in. However, when I call the built in AuthenticationForm class, create an instance with the post data, and try to authenticate the user, I get no user returned and authentication fails. All the code for the views.py file is below. I have tried reading the AuthenticationForm source code, but none of that is helping. Any suggestions?

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.db import models
from django import forms
from django.forms import EmailField
from django.forms import CharField
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User


class SignUpForm(UserCreationForm):
    email = EmailField(label=_("Email address"), required=True, help_text=_("Required."))

    class Meta:
        model = User
        fields = ('email', 'username', 'first_name', 'last_name',)

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        user.firstName = self.cleaned_data["first_name"]
        user.lastName = self.cleaned_data["last_name"]
        user.set_password(self.cleaned_data["password1"])

        if commit:
            user.save()
            return user




def signup(request):
    if request.method == 'POST': # if sending data to the server
        form = SignUpForm(request.POST)# creates form from request data
        if form.is_valid():
            user = form.save() # at this point, need to set user permissions, attach to user themselves? Add permissions this way?
            #            user.groups.set('tutors')
            user.save()

#            print(user.get_all_permissions()) # gets all permissions of user
#            print(user.groups.values_list('name',flat=True))
            # set permissions here
            # once set permissions, can close off the rest of the site and continue
            return redirect('/user/signup')
        else: # if form isn't valid
            errorMessage = True # sets flag to display error in HTML page
            form = SignUpForm()
            dict = {'errorMessage': errorMessage, 'form': form}
            return render(request, 'user/signup.html', dict) #
# pass in
    else: # if get request, return new form
        form = SignUpForm()
        return render(request, 'user/signup.html', {'form': form}) # return rendered form




#
#
#
def log_in(request):
    if request.method == 'POST':
        # need to get user from log in form

        form = AuthenticationForm(request.POST) # form isn't valid because user name isn't being passed in?
        print(form)
        user = form.get_user()
        print(user)
        # authentication form expects user name and password, needs to accept email
        if form.is_valid(): # WHY ISN'T THIS VALID
            # where to get user?
            user = form.get_user
            print("Groups: ")
            print(user.groups)

            return render(request, 'user/log_in.html', {'form': form}) #

        else:
            print("Not valid")
            return render(request, 'user/log_in.html', {'form': form}) #

````
1
  • Update: here is the authentication backend setting in my settings.py file: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', ] Commented Jan 11, 2019 at 1:16

3 Answers 3

4

For future ref: Need to use AuthenticationForm with this parameter:

form = AuthenticationForm(data=request.POST)

This will let it validate correctly.

Sign up to request clarification or add additional context in comments.

4 Comments

Right. Curious where did you find that information? I can't find any information regarding data in this page
Agreed, there is no exact documentation for that parameter, but the document certainly does pass parameters in as data check out this on the document: from django.contrib.auth import update_session_auth_hash def password_change(request): if request.method == 'POST': form = PasswordChangeForm(user=request.user, data=request.POST) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) else: ...
Go ahead and search that on the link that you posted and you'll find it. My thought might be that it's a superclass parameter that they don't discuss for the form subclasses.
Yeah saw that... Super finding between.
0

I think question is too old, but still.

The Authentication Form (/site-packages/django/contrib/auth/forms.py) is a subclass of forms.Form (/site-packages/django/forms/forms.py).

Check forms.Form class

def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
             initial=None, error_class=ErrorList, label_suffix=None,
             empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None):
    self.is_bound = data is not None or files is not None

Until unless is_bound is not set to True, is_valid will return False.

Comments

0

You can try this.Do let me know:

def log_in(request):
    if request.method == 'POST':
        form = AuthenticationForm(request=request,data=request.POST)
        if form.is_valid():
            user_name = form.cleaned_data['username']
            user_pass = form.cleaned_data['password']
            user = authenticate(username=user_name ,password = user_pass)
            if user is not None:
                login(request,user)
                return redirect('home')
    else:
        form = AuthecticationForm()
    return render(request, 'user/log_in.html', {'form': form})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.