Django In Create Login Page Using (User Model)

 How To Create Login Page In Django Using  Django  User Model .





Step 1: Open Models.py and write in this Code.

// models.py 

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 Urls.py in your Django Project



// urls.py

from django.contrib import admin
from django.urls import path,include

from .import views

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



] 



Step 3 : Create templates folder in Django Project.
Step 4 : template Folder in create Login Page.
Step 5 : Open Login.html in Write in this code.





// 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>Login To Your Account</h2>
						<form method="post">
                            {% csrf_token %}
                            {% for field in form %}
                            {{ field.errors }}
                            <label>{{field.label_tag}}</label>
                            <p>{{ field }}</p>
                            {% endfor %}
                            <a href="{% url 'password_reset' %}" style="float:right;">Forgot Password ?</a><br>

                            <button class="btn btn-default" type="submit">Login</button>
                            <a href="{% url 'signup' %}"><span style="color:black;margin-left:120px;">Create Your Account&nbsp;&rarr;</span></a>
                        </form>
               </div>
            </div>
        </div>
</section>

{% endblock %}
Step 6 : 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)

Post a Comment

0 Comments