Django In Create Signup Page Using Django User Model

How to Create Django in Signup Page using Django User model.


Step 1 : Open Models.py file in Django Project.

// models.py

from django.db import models

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


class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True,label='Email',error_messages={'exists': 'This Already Exists'})

    class Meta:
        model = User
        fields = ('username','email','password1','password2')

    def __init__(self, *args, **kwargs):
        super(UserCreateForm, self).__init__(*args, **kwargs)

        self.fields['username'].widget.attrs['placeholder'] = 'User Name'
        self.fields['email'].widget.attrs['placeholder'] = 'Email'
        self.fields['password1'].widget.attrs['placeholder'] = 'Password'
        self.fields['password2'].widget.attrs['placeholder'] = 'confirm Password'

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user

    def clean_email(self):
        if User.objects.filter(email=self.cleaned_data['email']).exists():
            raise forms.ValidationError(self.fields['email'].error_message['exists'])
        return self.cleaned_data['email']

Step 2: Open Views.py in Django Project.


// views.py

def signup(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            new_user = authenticate(
                username = form.cleaned_data['username'],
                password = form.cleaned_data['password1'],
            )
            login(request,new_user)
            return redirect('index')
    else:
        form = UserCreateForm()

    context = {
        'form':form,
    }
    return render(request,'registration/signup.html',context)

Step 3 : Open urls.py file.


// urls.py

from django.urls import path,include
from .import views

urlpatterns = [
    

    path('signup',views.signup,name='signup'),
    path('accounts/',include('django.contrib.auth.urls')),



] 
Step 4 : Create signup.html file in template folder.
Step 5 : write a code in signup.html



// signup.html

{% extends 'master.html' %}
{% block body %}
<section id="form" style="margin-left:30%;"><!--form-->
		<div class="container">
			<div class="col-sm-4 col-sm-offset-1">
               <div class="signup-form"><!--login form-->
						<h2>New User Signup</h2>
						<form method="post">
                            {% csrf_token %}
                            {% for field in form %}
                            {{ field.errors }}
                            <p>{{ field }}</p>
                            {% endfor %}

                            <button class="btn btn-default" type="submit">Signup</button><br>
                            <span style="margin-left:80px;">Already have an account</span>&nbsp;<a href="{% url 'login' %}">Log In</a>
                        </form>
               </div>
            </div>
        </div>
</section>

{% endblock %}

Post a Comment

0 Comments