Django User Registration Authentication – SignUpView

 

Django User Registration Authentication – SignUpView

We can implement simple sign up registration by using in-built UserCreationForm Auth Form(signup class based view). We will be using CreateView in View. We can create sign up using only username and password. But we are adding extra fields in forms.py ( django create user form ) while registration like first last name and email.

urls.py

from django.urls import path
from core.views import SignUpView

urlpatterns = [
    path('signup/', SignUpView.as_view(), name='signup'),
]

views.py

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from core.forms import SignUpForm

# Sign Up View
class SignUpView(CreateView):
    form_class = SignUpForm
    success_url = reverse_lazy('login')
    template_name = 'commons/signup.html'

forms.py

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

# Sign Up Form
class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional')
    email = forms.EmailField(max_length=254, help_text='Enter a valid email address')

    class Meta:
        model = User
        fields = [
            'username', 
            'first_name', 
            'last_name', 
            'email', 
            'password1', 
            'password2', 
            ]

signup.html

{% extends 'base.html' %}

{% block title %}Sign Page{% endblock title %}

{% block content %} 
    <h2>Sign Page</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Register</button>
        <br><br>
        <a href="{% url 'home' %}">Home</a>
    </form>
{% endblock content %}
Previous
Next Post »