Skip to main content

How to create user-register form,login,logout and also make a profile of each user register in Django?

Django provides a quite easy way to create a User-Registration as all are already presents in the Django we just know how to use this..Here, we will see how to easily implement this and create a profile of all users which are register.This article will be an interesting and important so please read out seriously.


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

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

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
from django.conf.urls.static import static
from users import views as user_views
from django.contrib.auth import views as auth_views
urlpatterns = [
    path('register/',user_views.register, name='register'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('profile/', user_views.profile, name='profile'),
    path('admin/', admin.site.urls),
]

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


In Django their is already a user Model is present, we just need to import this 
In the model we create a user Profile in which their is User information and image.We also create a save method which override the save method 
to resize the size of the image. from PIL import Image we import the image from the pillow library and check the height and width in the "if" condition in the save method
and finally save the image in "300x300" so that the image will be fit and take less time to reload in the server.

"users/models.py" 

from django.db import models
from django.contrib.auth.models import User
from PIL import Image

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='1.jpg'upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    # def save(self):
    #     super().save()
    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)
       
        img = Image.open(self.image.path)
        
        if img.height > 300 or img.width > 300:
            output_size = (300300)
            img.thumbnail(output_size)
            img.save(self.image.path)



Now Register the model in the admin.py
"users/admin.py"


After creating a class in the model we migrate the models in our model and the commands for that are:
 python manage.py makemigrations
 python manage.py migrate


Now we have to create a super-user in Django it is quite simple we have to just type the commad

 python manage.py create supersuser:


In Django it is quite easy as the django has an inbuilt forms only we have to know how to 
implement this for that we make a forms.py file in our users app.We have to also import the User model which is inbuilt in Django and "from django.contrib.auth.forms import UserCreationForm"
In the userRegister form we have to inherit the UserCreation Form and also create an email field as it is not present in the "UserCreationForm"
Similarly in the "UserUpdateForm" class we also assign an email field.
We are also creating a ProfileUpdateForm to update the profile image.Now,see how we join these two classes in the "views.py".
  
"users/forms.py"

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

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

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


class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username''email']


class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['image']



In the "views.py" we create  a "register" function based views and check the validation of the form and if the form is valid than redirect the user in the login page.
And in the profile function firstly, import a "@login_required" decorator so that only those users which are already login can update the profile and i think the logic is pretty simple right.

"users/views.py" 

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Your account has been created! 
You are now able to log in')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')

    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'u_form': u_form,
        'p_form': p_form
    }

    return render(request, 'users/profile.html', context)





Now, we have to make a templates folder in the users app and in the template we also make an users folder and now make a register.html,login.html, logout.html and profile.html
 
"users/templates/users/register.html"

{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/
bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
crossorigin="anonymous">

    
        <title>Registration</title>
</head>
<body>
<div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Join Today</legend>
                {{ form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Sign Up</button>
            </div>
        </form>
        <div class="border-top pt-3">
            <small class="text-muted">
                Already Have An Account? <a class="ml-2" href="{% url 'login' %}">
                Sign In</a>
            </small>
        </div>
    </div>
        <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity=
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" 
crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/
popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/
ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/
bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/
JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>

</html>





Django-crispy-forms has built-in support for different CSS frameworks, known as template packs within django-crispy-forms:
To install the crispy-forms the command is :
   pip install django-crispy-forms
    
After installing we have to also add the "crispy_forms" in the  "INSTALLED_APPS" and load the crispy form tag in the top of our template.

"users/templates/users/login.html"

{% load crispy_forms_tags %}
<!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">
        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/
bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+
058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
 <title>Login</title>
<body>
<div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Log In</legend>
                {{ form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Login</button>
            </div>
        </form>
        <div class="border-top pt-3">
            <small class="text-muted">
                Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a>
            </small>
        </div>
    </div>



        <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" 
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/
GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/
popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/
ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/
bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/
JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>
</html>


   

"users/templates/users/logout.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">
        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

        <!-- <link rel="stylesheet" type="text/css" href="#"> -->
    
    <title>logout</title>
<body>
 <h2>You have been logged out</h2>
    <div class="border-top pt-3">
        <small class="text-muted">
            <a href="{% url 'login' %}">Log In Again</a>
        </small>
    </div>
      


  <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" 
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/
GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/
popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/
ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/
bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/
JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>
</html>


"users/templates/users/profile.html"

{% load crispy_forms_tags %}
<!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">
        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/
4.0.0/css/bootstrap.min.css" 
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
crossorigin="anonymous">

        <!-- <link rel="stylesheet" type="text/css" href="#"> -->
    
    <title>Profile</title>


<body>
<div class="content-section " >
  <div class="media">
    <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
    <div class="media-body">
      <h2 class="account-heading">{{ user.username }}</h2>
      <p class="text-secondary">{{ user.email }}</p>
    </div>
  </div>
  <!-- FORM HERE -->
  <form method="POST" enctype="multipart/form-data" >
    {% csrf_token %}
    <fieldset class="form-group">
        <legend class="border-bottom mb-4">Profile Info</legend>
        {{ u_form|crispy }}
        {{ p_form|crispy }}
    </fieldset>
    <div class="form-group">
        <button class="btn btn-outline-info" type="submit">Update</button>
    </div>
</form>
</div>
  <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" 
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/
GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/
popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/
ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/
bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/
JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>
</html>


   


That's all about this post. I hope you all are understand this and if anybody wants to update this or find anything irrelevant please comment below,I will definitely check it and if improvement needed definitely do.





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...

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)   ...