Max
Max

Reputation: 181

Django Built In AuthenticationForm Not Validating User

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}) #

````

Upvotes: 1

Views: 1592

Answers (3)

Asif Mahmud
Asif Mahmud

Reputation: 3

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})

Upvotes: 0

Max
Max

Reputation: 181

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

form = AuthenticationForm(data=request.POST)

This will let it validate correctly.

Upvotes: 4

Shubham Kaushik
Shubham Kaushik

Reputation: 11

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.

Upvotes: 0

Related Questions