Django Authentication

Posted by Daksh on Wednesday, August 10, 2022

Implementing a signup form in Django

Inside your Django core app, create a new file called forms.py and add the following code:

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

# this code snippet uses tailwindcss classes, 
# you can also style theses forms in the way you want inside the template.html file
# refer django-forms post for more details
class SignupForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    username = forms.CharField(widget=forms.TextInput(attrs={
        'placeholder': 'Your username',
        'class': 'w-full py-4 px-6 rounded-xl'
    }))
    email = forms.CharField(widget=forms.EmailInput(attrs={
        'placeholder': 'Your email address',
        'class': 'w-full py-4 px-6 rounded-xl'
    }))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs={
        'placeholder': 'Your password',
        'class': 'w-full py-4 px-6 rounded-xl'
    }))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={
        'placeholder': 'Repeat password',
        'class': 'w-full py-4 px-6 rounded-xl'
    }))

Inside the core/views.py file, add the following code:

from .forms import SignUpForm

def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)

        if form.is_valid():
            form.save()

            return redirect('/login/')
    else:
        form = SignupForm()

    return render(request, 'core/signup.html', {
        'form': form
    })

Implementing login in Django is quite straightforward.

Inside the core/forms.py file, add the following code:

from django import forms
from django.contrib.auth.forms import AuthenticationForm
class LoginForm(AuthenticationForm):
    username = forms.CharField(widget=forms.TextInput(attrs={
        'placeholder': 'Your username',
        'class': 'w-full py-4 px-6 rounded-xl'
    }))
    password = forms.CharField(widget=forms.PasswordInput(attrs={
        'placeholder': 'Your password',
        'class': 'w-full py-4 px-6 rounded-xl'
    }))

Inside the core/url.py file, add the following code:

from django.contrib.auth import views as auth_views
from .forms import LoginForm

urlpatterns = [
    path('login/', auth_views.LoginView.as_view(authentication_form=LoginForm, template_name='core/login.html'), name='login'),
]

And finally, create a login template inside the core/templates/core folder.

After a successful login, the user will be redirected to accounts/profile/ page. To change this, go to project/settings.py file and add the following code:

# redirect to home page after login
# core is the name of the app
# you can also use '/login/'
LOGIN_URL = 'core:login' 
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'