Django Login and Logout step by step

Open command prompt in windows 

then in command prompt  type    d:  

and press enter .

and use following commands 

To create folder  myap -execute the following command:

D:\> mkdir myap

To  go  myap folder path -execute the following command:

D:\>cd myap 

To create a virtual environment for your project, open a new command prompt, navigate to the myap  folder where you want to create your project and then execute the following command:-

D:\myap>python -m venv env

In the command prompt, ensure your virtual environment is active, and execute the following command:

D:\myap>env\Scripts\activate

execute the following command to install django.

D:myap>pip install django

run the following command - This will create a myproject  directory in your current directory

D:\myap>django-admin startproject  myproject

then go to myproject folder path type following command :-


D:\myap>cd myproejct


To create your app, make sure you’re in the your project  directory &  type this command:


D:\myap\myproejct>python manage.py  startapp hello 

That’ll create a directory hello app folder inside my_project folder:

after it open your myap folder inside it you will see my_project folder 



and inside my_project folder you will see following structure:-

 

D:\mywork\myproejct>python manage.py runserver.



Step 1:-  Write   code for models.py file:-

from django.db import models


# Create your models here.


class ContactForm(models.Model):

        


    fullname= models.CharField(max_length=100)

    email= models.EmailField()

    contact= models.CharField(max_length=50)

    message= models.CharField(max_length=200)


write code for admin.py file :-

from django.contrib import admin

from .models import contactEnquiry,ContactForm


# Register your models here.


admin.site.register(contactEnquiry)

admin.site.register(ContactForm)



list_display = ['fullname', 'email','contact','message' ]


write  code for   forms.py file :-

from django import forms

from .models import ContactForm

from django.contrib.auth.forms import UserCreationForm

from django.contrib.auth.models import User


class FormContactForm(forms.ModelForm):

    class Meta:

        model= ContactForm

        fields= ["fullname", "email", "contact", "message"]


class NewUserForm(UserCreationForm):

    email = forms.EmailField(required=True)


    class Meta:

        model = User

        fields = ["username", "email", "password1", "password2"]


Step 2:-

write  code for urls.py file:-

from django.urls import path


from .import views



urlpatterns=[

path('',views.index,name='index'),

path('home/',views.home,name='home'),

path('homepage/',views.homepage,name='homepage'),

path('about/',views.about,name='about'),


path('showform/', views.showform),

path('search/', views.search,name='search'),

path('search1/', views.search1,name='search1'),


path('editemp/<int:id>', views.editemp, name='editemp'),

path('updateemp/<str:id>', views.updateemp, name='updateemp'),


path('saveenquiry/',views.saveenquiry,name="saveenquiry"),

     path("register", views.register_request, name="register"),

         path("login", views.login_request, name="login"),

         path("logout", views.logout_request, name= "logout"),









]




Write code for views.py file :-

from urllib import request

from django.shortcuts import render,redirect

from  hello.models  import ContactForm,contactEnquiry

from  hello.forms import FormContactForm

from .forms import NewUserForm


from django.http import HttpResponse

from django.contrib.auth import login, authenticate,logout #add this

from django.contrib import messages

from django.contrib.auth.forms import AuthenticationForm

from django.db.models  import Q


def index(request):

    

    data="50"

    

    request.session['paid']=data

 


    return render(request, "home.html",{'data':data})


def home(request): 

    data='5000'

    

    

    print(request.session['paid']) 

    return render(request, "home.html",{'data':data})


def about(request):


    data=request.session.get('paid')


    return render(request, "about.html",{'data':data})


def homepage(request):


   

    return render(request, "homepage.html")





def showform(request):

    form= FormContactForm(request.POST or None)

    if form.is_valid():

        form.save()

  

    context= {'form': form }

        

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


def saveenquiry(request):


 


 if request.method=="POST":

        

  email=request.POST['email']

  name=request.POST['name']


  


 message=request.POST['msg']


 en=contactEnquiry(name=name,email=email,message=message)


 en.save()


 n='data inserted'


 return render(request,"contact.html",{'n':n})



def home(request):

 serviceData=ContactForm.objects.all()

 data={'serviceData':serviceData

        }


 return render(request,"home.html",data)


def  editemp(request,id):

 data=ContactForm.objects.get(id=id)

 return render(request, "edit.html",{'editupdaterecord':data})


def  updateemp(request,id):

 if request.method=='POST':

  pi=ContactForm.objects.get(id=id)

  form= FormContactForm(request.POST ,instance=pi)

 if form.is_valid():

        

        form.save()

 msg="record updated"

 return render(request, "update.html",{'editupdaterecord':msg})

      


def search(request):

    if request.GET.get('myform'): # write your form name here      

        book_name =  request.GET.get('myform')  

           

        try:

                

            status = ContactForm.objects.filter(fullname__icontains=book_name)

            return render(request,"search1.html",{"books":status})

        except:

            return render(request,"search1.html",{'books':status})

    else:

        return render(request, 'search1.html', {'books':status})


def search1(request):

 if 'q'  in request.GET:

    q=request.GET['q']

    multiple_q=Q(Q(fullname=q)| Q(message=q))

    data=ContactForm.objects.filter(multiple_q)

    

 else:

    data =ContactForm.objects.all()

    

 return render(request,'search1.html',{

 'data':data

 })


 


def login_request(request):

    if request.method == "POST":

        form = AuthenticationForm(request, data=request.POST)

        if form.is_valid():

            username = form.cleaned_data.get('username')

            password = form.cleaned_data.get('password')

            user = authenticate(username=username, password=password)

            if user is not None:

                login(request, user)

                messages.info(request, f"You are now logged in as {username}.")

                return redirect("homepage")

            else:

                messages.error(request,"Invalid username or password.")

        else:

            messages.error(request,"Invalid username or password.")

    form = AuthenticationForm()

    return render(request, 'login.html', context={"login_form":form})


def register_request(request):

    if request.method == "POST":

        form = NewUserForm(request.POST)

        if form.is_valid():

            user = form.save()

            login(request, user)

            messages.success(request, "Registration successful." )

            return redirect("home")

        messages.error(request, "Unsuccessful registration. Invalid information.")

    form = NewUserForm()

    return render (request, 'register.html', context={"register_form":form})


def logout_request(request):

    logout(request)

    messages.info(request, "You have successfully logged out.") 

    return redirect("homepage")



Step   3:-  write code for templates folder  register.html file :-

<div class="container py-5">

    <h1>Register</h1>

    <form method="POST">

        {% csrf_token %}

        {{ register_form }}                    

        <button class="btn btn-primary" type="submit">Register</button>

    </form>

    <p class="text-center">If you already have an account, <a href="hello/login">login</a> instead.</p>

</div>


Write code for login.html file   :-

<!--Login--> 

<div class="container py-5">

    <h1>Login</h1>

    <form method="POST">

      {% csrf_token %}

      {{ login_form}}

      <button class="btn btn-primary" type="submit">Login</button>

    </form>

    <p class="text-center">Don't have an account? <a href="hello/register">Create an account</a>.</p>

  </div>


Write code for homepage.html file  :-

<!--Navbar-->

<nav class="navbar navbar-expand-lg navbar-light bg-light">

    <a class="navbar-brand" href="#">Navbar</a>

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="False" aria-label="Toggle navigation">

      <span class="navbar-toggler-icon"></span>

    </button>

    <div class="collapse navbar-collapse" id="navbarText">

      <ul class="navbar-nav mr-auto">

        {% if user.is_authenticated %}

        

        <li class="nav-item">

          <a class="nav-link" href="{% url 'logout' %}">Logout</a>

        </li>

        <li class="nav-item">

          <a class="nav-link" href="#">Welcome, {{user.username}}</a>

        </li>

  

        {% else %}

  

        <li class="nav-item">

          <a class="nav-link" href="{% url 'login' %}">Login</a>

        </li>

  

        {% endif %}

      </ul>

    </div>

  </nav>


Previous
Next Post »