custom UserCreationForm in Forms.py won't import into Views.py

Viewed 33

I am new to Python and Django and I'm trying to create a basic user authentication system. I want to add an extra email field in the user registration. I don't understand why the UserCreationForm won't import into views.py. I also created a regular forms.Form for the user login in the same forms.py folder and it imports fine into views.py.

forms.py

from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)

            if not user:
                raise forms.ValidationError('This user does not exist')
            if not user.check_password(password):
                raise forms.ValidationError('Incorrect password')
            if not user.is_active:
                raise forms.ValidationError('This user is not active')
        return super(UserLoginForm, self).clean(*args, **kwargs)

    class UserRegisterForm(UserCreationForm):
        email = forms.EmailField(label='Email address')
        email2 = forms.EmailField(label='Confirm email')

        class Meta:
            model = User
            fields = [
                'username',
                'email',
                'email2',
                'password'
            ]

        def clean_email(self):
            email = self.cleaned_data.get('email')
            email2 = self.cleaned_data.get('email2')
            if email != email2:
                raise forms.ValidationError("emails must match")
            email_qs = User.objects.filter(email=email)
            if email_qs.exists():
                raise forms.ValidationError(
                    "This email is already being used"
                )
            return email

views.py

from django.shortcuts import render, redirect
from django.contrib.auth import (
    authenticate,
    login,
    logout
)

from .forms import UserLoginForm 

from .forms import UserRegisterForm


def login_view(request):
    next = request.GET.get('next')
    form = UserLoginForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        login(request, user)
        if next:
            return redirect(next)
        return redirect('/')

    context = {
        'form': form,
    }

    return render(request, 'login.html', context)


def register_view(request):
    next = request.GET.get('next')
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=False)
        password = form.save(commit=False)
        user.set_password(password)
        user.save()
        new_user = authenticate(username=user.username, password=password)
        login(request, new_user)
        if next:
            return redirect(next)
        return redirect('/')

    context = {
        'form': form,
    }

    return render(request, 'signup.html', context)


def logout_view(request):
    logout(request)
    return redirect('/')
1 Answers

So basically your indentation was off in forms.py

Here is the fixed indentation code:

from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)

            if not user:
                raise forms.ValidationError('This user does not exist')
            if not user.check_password(password):
                raise forms.ValidationError('Incorrect password')
            if not user.is_active:
                raise forms.ValidationError('This user is not active')
        return super(UserLoginForm, self).clean(*args, **kwargs)

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField(label='Email address')
    email2 = forms.EmailField(label='Confirm email')

    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'email2',
            'password'
        ]

    def clean_email(self):
        email = self.cleaned_data.get('email')
        email2 = self.cleaned_data.get('email2')
        if email != email2:
            raise forms.ValidationError("emails must match")
        email_qs = User.objects.filter(email=email)
        if email_qs.exists():
            raise forms.ValidationError(
                "This email is already being used"
            )
        return email
Related