Skip to main content

WHAT IS DJANGO AUTHENTICATION?AND HOW TO MANUALLY WRITE THE CODE FOR THE SIGNUP, LOGIN AND LOGOUT?

In this post we see how to manually write the code for the user Registeration , Login and Logout.

firstly we have to start a project and than start an app:

    django-admin startproject user-authentication
    $ cd user-authentication
    $ python manage.py startapp accounts

Once we have created an app we have to add this app in the INSTALLED_APPS  in settings.py.

Than we have to add the path of the accounts app:

"main project urls.py"
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
urlpatterns = [
    path('accounts/',include('accounts.urls')),
    path('admin/', admin.site.urls),
]

if settings.DEBUG:
    urlpatterns=urlpatterns+static(settings.MEDIA_URL,document_root=
        settings.MEDIA_ROOT)
                                                                                                                                                                        

Note that in the main urls we include the accounts app and than we have to include all our urls in the accounts urls.py file..For that we have to make an urls.py file in our accounts app.
and than include all these urls.

"accounts/urls.py"

from django.urls import path

from . import views

urlpatterns=[
    path('register',views.register,name='register'),
    path("login",views.login,name="login"),
    path("logout",views.logout,name="logout")
    
]

Than we have to write the code in the accounts view.py file...

"accounts/views.py"

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User, auth
from django.urls import path, include
from django.contrib.sessions.models import Session
# Create your views here.

def register(request):

        if  request.method == 'POST':
                first_name = request.POST['first_name']
                last_name = request.POST['last_name']
                username = request.POST['username']

                password1 = request.POST['password1']
                password2 = request.POST['password2']
                email = request.POST['email']

                if password1 == password2:
                    if User.objects.filter(username=username).exists():
                        messages.info(request, 'Username taken')
                        return redirect('register')

                    elif User.objects.filter(email=email).exists():
                        messages.info(request, 'Email taken')
                        return redirect('register')
                    else:
                        user = User.objects.create_user(
                        username=username, password=password1, email=email, 
                        first_name=first_name, last_name=last_name)
                        user.save();
                        # print('user created')
                        return redirect('login')
                else:
                    messages.info(request, 'password not matching..')
                    return redirect('register')
                return redirect('/') #return you in the home page

        else:
            return render(request,'register.html')



def login(request):
    if request.session.has_key('is_logged'):
            return redirect("/")

    if request.method == 'POST':
       username = request.POST['username']
       password = request.POST['password']

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

       if user is not None:
           auth.login(request, user)
           request.session['is_logged'] = True
           return redirect("/")

       else:
           messages.info(request, 'invalid credentials')
           return redirect('login')

    else:
        return render(request, 'login.html')



def logout(request):
      if request.session.has_key('is_logged'):
        del request.session['is_logged']
      auth.logout(request)
      return redirect('/')       
      


In this view firstly we define a function based view name as register and pass the request.
If the request is POST than we have to check the condition such is username is available or already 
taken password and confirm password is matching or not etc if any of the condition is failed than 
an error message is printed.
  
After that we have to login the user and when the user is login we also create a session which has a key
("is_logged").if the session is present than the user do not have to give the credentials again.
in the login function there is also an auth.authenticate which authenticate the user name and the password.

Than in the logout function firstly we delete the session and than auth.logout request which logout the current user and return redirect('/')
will return to the home page..

In the register template we write the code :

"register.html"

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration</title>
</head>
<style>@import url(https://fonts.googleapis.com/css?family=Roboto:400,300,500);
    *:focus {
      outlinenone;
    }
    
    body {
      margin0;
      padding0;
      background#DDD;
      font-size16px;
      color#222;
      font-family'Roboto'sans-serif;
      font-weight300;
    }
    
    #login-box {
      positionrelative;
      margin5% auto;
      width600px;
      height400px;
      background#FFF;
      border-radius2px;
      box-shadow0 2px 4px rgba(0000.4);
    }
    
    .left {
      positionabsolute;
      top0;
      left0;
      box-sizingborder-box;
      padding40px;
      width300px;
      height400px;
    }
    
    h1 {
      margin0 0 20px 0;
      font-weight300;
      font-size28px;
    }
    
    input[type="text"],
    input[type="password"] {
      displayblock;
      box-sizingborder-box;
      margin-bottom20px;
      padding4px;
      width220px;
      height32px;
      bordernone;
      border-bottom1px solid #AAA;
      font-family'Roboto'sans-serif;
      font-weight400;
      font-size15px;
      transition0.2s ease;
    }
    
    input[type="text"]:focus,
    input[type="password"]:focus {
      border-bottom2px solid #16a085;
      color#16a085;
      transition0.2s ease;
    }
    
    input[type="submit"] {
      margin-top28px;
      width120px;
      height32px;
      background#16a085;
      bordernone;
      border-radius2px;
      color#FFF;
      font-family'Roboto'sans-serif;
      font-weight500;
      text-transformuppercase;
      transition0.1s ease;
      cursorpointer;
    }
    
    input[type="submit"]:hover,
    input[type="submit"]:focus {
      opacity0.8;
      box-shadow0 2px 4px rgba(0000.4);
      transition0.1s ease;
    }
    
    input[type="submit"]:active {
      opacity1;
      box-shadow0 1px 2px rgba(0000.4);
      transition0.1s ease;
    }
    
    .or {
      positionabsolute;
      top180px;
      left280px;
      width40px;
      height40px;
      background#DDD;
      border-radius50%;
      box-shadow0 2px 4px rgba(0000.4);
      line-height40px;
      text-aligncenter;
    }
    
    .right {
      positionabsolute;
      top0;
      right0;
      box-sizingborder-box;
      padding40px;
      width300px;
      height400px;
      backgroundurl('https://goo.gl/YbktSj');
      background-sizecover;
      background-positioncenter;
      border-radius0 2px 2px 0;
    }
    
    .right .loginwith {
      displayblock;
      margin-bottom40px;
      font-size28px;
      color#FFF;
      text-aligncenter;
    }
    
    button.social-signin {
      margin-bottom20px;
      width220px;
      height36px;
      bordernone;
      border-radius2px;
      color#FFF;
      font-family'Roboto'sans-serif;
      font-weight500;
      transition0.2s ease;
      cursorpointer;
    }
    
    button.social-signin:hover,
    button.social-signin:focus {
      box-shadow0 2px 4px rgba(0000.4);
      transition0.2s ease;
    }
    
    button.social-signin:active {
      box-shadow0 1px 2px rgba(0000.4);
      transition0.2s ease;
    }
    
    button.social-signin.facebook {
      background#32508E;
    }
    
    button.social-signin.twitter {
      background#55ACEE;
    }
    
    button.social-signin.google {
      background#DD4B39;
    }</style>
<body>
        

    <div id="login-box">
        <div class="left">
          <h1>Sign up</h1>
          <form action="register" method="post">
    
          {% csrf_token %}  
          <input type="text" name="first_name" placeholder="First Name" />
          <input type="text" name="last_name" placeholder="Last Name" />
          <input type="text" name="username" placeholder="User Name" />
          <input type="text" name="email" placeholder="E-mail" />
          <input type="password" name="password1" placeholder="Password" />
          <input type="password" name="password2" placeholder="Retype password" />
          
          <input type="submit" />
        </form>
        </div>
        
        <div class="right">
          <span class="loginwith">Sign in with<br />social network</span>
          
          <button class="social-signin facebook">Log in with facebook</button>
          <button class="social-signin twitter">Log in with Twitter</button>
          <button class="social-signin google">Log in with Google+</button>
        </div>
        <div class="or">OR</div>
      </div>
    <div>
        {% for message in messages %}
       <h3> {{message}} </h3>
        {% endfor %}
    </div>


</body>
</html>

Don't confuse in this code we just copy-paste the already present  free register template so that our User Interface looks cool..😃

Similarly in,"login.html"

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    @import url(https://fonts.googleapis.com/css?family=Open+Sans);
    .btn { displayinline-block; *displayinline; *zoom1padding4px 10px 4pxmargin-bottom0font-size13pxline-height18pxcolor#333333text-aligncenter;text-shadow0 1px 1px rgba(2552552550.75); vertical-alignmiddlebackground-color#f5f5f5background-image-moz-linear-gradient(top#ffffff#e6e6e6); background-image: -ms-linear-gradient(top#ffffff#e6e6e6); background-image-webkit-gradient(linear0 00 100%from(#ffffff), to(#e6e6e6)); background-image-webkit-linear-gradient(top#ffffff#e6e6e6); background-image-o-linear-gradient(top#ffffff#e6e6e6); background-imagelinear-gradient(top#ffffff#e6e6e6); background-repeatrepeat-xfilter: progid:dximagetransform.microsoft.gradient(startColorstr=#ffffff, endColorstr=#e6e6e6, GradientType=0); border-color#e6e6e6 #e6e6e6 #e6e6e6border-colorrgba(0000.1rgba(0000.1rgba(0000.25); border1px solid #e6e6e6-webkit-border-radius4px-moz-border-radius4pxborder-radius4px-webkit-box-shadowinset 0 1px 0 rgba(2552552550.2), 0 1px 2px rgba(0000.05); -moz-box-shadowinset 0 1px 0 rgba(2552552550.2), 0 1px 2px rgba(0000.05); box-shadowinset 0 1px 0 rgba(2552552550.2), 0 1px 2px rgba(0000.05); cursorpointer; *margin-left.3em; }
    .btn:hover.btn:active.btn.active.btn.disabled.btn[disabled] { background-color#e6e6e6; }
    .btn-large { padding9px 14pxfont-size15pxline-heightnormal-webkit-border-radius5px-moz-border-radius5pxborder-radius5px; }
    .btn:hover { color#333333text-decorationnonebackground-color#e6e6e6background-position0 -15px-webkit-transition: background-position 0.1s linear-moz-transition: background-position 0.1s linear-ms-transition: background-position 0.1s linear-o-transition: background-position 0.1s lineartransition: background-position 0.1s linear; }
    .btn-primary.btn-primary:hover { text-shadow0 -1px 0 rgba(0000.25); color#ffffff; }
    .btn-primary.active { colorrgba(2552552550.75); }
    .btn-primary { background-color#4a77d4background-image-moz-linear-gradient(top#6eb6de#4a77d4); background-image: -ms-linear-gradient(top#6eb6de#4a77d4); background-image-webkit-gradient(linear0 00 100%from(#6eb6de), to(#4a77d4)); background-image-webkit-linear-gradient(top#6eb6de#4a77d4); background-image-o-linear-gradient(top#6eb6de#4a77d4); background-imagelinear-gradient(top#6eb6de#4a77d4); background-repeatrepeat-xfilter: progid:dximagetransform.microsoft.gradient(startColorstr=#6eb6de, endColorstr=#4a77d4, GradientType=0);  border1px solid #3762bctext-shadow1px 1px 1px rgba(0,0,0,0.4); box-shadowinset 0 1px 0 rgba(2552552550.2), 0 1px 2px rgba(0000.5); }
    .btn-primary:hover.btn-primary:active.btn-primary.active.btn-primary.disabled.btn-primary[disabled] { filternonebackground-color#4a77d4; }
    .btn-block { width100%display:block; }
    
    * { -webkit-box-sizing:border-box-moz-box-sizing:border-box-ms-box-sizing:border-box-o-box-sizing:border-boxbox-sizing:border-box; }
    
    html { width100%height:100%overflow:hidden; }
    
    body { 
        width100%;
        height:100%;
        font-family'Open Sans'sans-serif;
        background#092756;
        background-moz-radial-gradient(0% 100%ellipse coverrgba(104,128,138,.410%,rgba(138,114,76,040%),-moz-linear-gradient(top,  rgba(57,173,219,.250%rgba(42,60,87,.4100%), -moz-linear-gradient(-45deg,  #670d10 0%#092756 100%);
        background-webkit-radial-gradient(0% 100%ellipse coverrgba(104,128,138,.410%,rgba(138,114,76,040%), -webkit-linear-gradient(top,  rgba(57,173,219,.250%,rgba(42,60,87,.4100%), -webkit-linear-gradient(-45deg,  #670d10 0%,#092756 100%);
        background-o-radial-gradient(0% 100%ellipse coverrgba(104,128,138,.410%,rgba(138,114,76,040%), -o-linear-gradient(top,  rgba(57,173,219,.250%,rgba(42,60,87,.4100%), -o-linear-gradient(-45deg,  #670d10 0%,#092756 100%);
        background: -ms-radial-gradient(0% 100%ellipse coverrgba(104,128,138,.410%,rgba(138,114,76,040%), -ms-linear-gradient(top,  rgba(57,173,219,.25) 0%,rgba(42,60,87,.4) 100%), -ms-linear-gradient(-45deg,  #670d10 0%,#092756 100%);
        background-webkit-radial-gradient(0% 100%ellipse coverrgba(104,128,138,.410%,rgba(138,114,76,040%), linear-gradient(to bottom,  rgba(57,173,219,.250%,rgba(42,60,87,.4100%), linear-gradient(135deg,  #670d10 0%,#092756 100%);
        filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#3E1D6D', endColorstr='#092756',GradientType=1 );
    }
    .login { 
        positionabsolute;
        top50%;
        left50%;
        margin-150px 0 0 -150px;
        width:300px;
        height:300px;
    }
    .login h1 { color#ffftext-shadow0 0 10px rgba(0,0,0,0.3); letter-spacing:1pxtext-align:center; }
    
    input { 
        width100%
        margin-bottom10px
        backgroundrgba(0,0,0,0.3);
        bordernone;
        outlinenone;
        padding10px;
        font-size13px;
        color#fff;
        text-shadow1px 1px 1px rgba(0,0,0,0.3);
        border1px solid rgba(0,0,0,0.3);
        border-radius4px;
        box-shadowinset 0 -5px 45px rgba(100,100,100,0.2), 0 1px 1px rgba(255,255,255,0.2);
        -webkit-transition: box-shadow .5s ease;
        -moz-transition: box-shadow .5s ease;
        -o-transition: box-shadow .5s ease;
        -ms-transition: box-shadow .5s ease;
        transition: box-shadow .5s ease;
    }
    input:focus { box-shadowinset 0 -5px 45px rgba(100,100,100,0.4), 0 1px 1px rgba(255,255,255,0.2); }
    </style>
<body>

<div class="login">
    <h1>Login</h1>
    <form method="post">
        {%csrf_token%}
        <input type="text" name="username" placeholder="Username" required="required" />
        <input type="password" name="password" placeholder="Password" required="required" />
        <input type="submit" class="btn btn-primary btn-block btn-large">
    </form>
</div>
<div>
        {% for message in messages %}
            <h3> {{message}} </h3>
        {% endfor %}
    </div>
</body>
</html>      




Comments

Popular posts from this blog

How to create a form and validate the form?

 In this blog we will validate our form by using pure javascript..firstly we have to  make our form in HTML and apply some basic css design so that it looks nice. <!-- Data Validation Data validation is the process of ensuring that user input is clean, correct,  and useful. Typical validation tasks are: has the user filled in all required fields? has the user entered a valid date? has the user entered text in a numeric field? Most often, the purpose of data validation is to ensure correct user input. Validation can be defined by many different methods, and deployed in many different  ways. Server side validation is performed by...

currency converter code in python

 Hello guys, Today in this code i discuss how to convert any currency in python. This is an simple currency converter code. First we have to download the currency data from the google and don't worry i will also provide  this file.. "currency data" Argentine Peso 60.003324 0.016666 Australian Dollar 1.456434 0.686608 Bahraini Dinar 0.376000 2.659574 Botswana Pula 10.748595 0.093035 Brazilian Real 4.165726 0.240054 British Pound 0.769337 1.299820 Bruneian Dollar 1.347741 0.741982 Bulgarian Lev 1.764110 0.566858 Canadian Dollar 1.306715 0.765278 Chilean Peso 773.624384 0.001293 Chinese Yuan Renminbi 6.864835 0.145670 Colombian Peso 3332.909888 0.000300 Croatian Kuna 6.707817 0.149080 Czech Koruna 22.658193 0.044134 Danish Krone 6.740053 0.148367 Emirati Dirham 3.672500 0.272294 Euro 0.901975 1.108678 Hong Kong Dollar 7.769198 0.128713 Hungarian Forint 303.647304 0.003293 Icelandic Krona 123.937684 0.008069 Indian Rupe...