Do you want to build Login & Registration functionality ?
Don’t worry!! This blog will assist you in getting started with Django. It is a high-level Web Development Framework in Python. It is free and open source, has a thriving and active community, great documentation, and many options for support.
Let's learn how to use Django ?
Django is versatile and powerful framework, suitable for building any project.
Use Django to complete the task in a matter of minutes.
To finish your basic Django project, just adhere to a few simple steps.
Step 1 : To create a Django application, we must first create a project within PyCharm and write a command.
pip install django
The preceding command will download all Django files into a virtual environment.
Step 2 : Following that, we must use the command to create a Django project: Project_Name can depend on the developer.
django-admin startproject Project_Name
Step 3: Then we will create apps inside the apps directory, which is in the base directory and is parallel to manage. py ,in order to create an app in the base directory, we will use the following command:
python manage.py startapp appname
Step 4: We must include the app in the settings.py file after it has been created. There is a list called INSTALLED_APPS inside of settings.py. apps.appname must be added to the list of INSTALLED_APPS.The project directory will be modified as follows:
Project_Name
- Project_Name
- init.py
- asgi.py
- settings.py
- urls.py
- wsgi.py
- apps
- appname
- init.py
- admin.py
- apps.py
- models.py
- tests.py
- views.py
- appname
- manage.py
- squlite.db
Step 5: Creating Templates
- Then, in parallel with manage.py, we will make a template directory in the base directory.
- After that, we need to establish a subdirectory named “registration,” and inside of it, we’ll construct a login and registration template file (HTML file).
Login file :
Registration file :
Registration Form
Step 6: Create your models here.
- We will build a model that serves as a table for storing the data in a database after developing the user interface. The fields we require are specified by that model.
- In the beginning, we must import AbstractUser from django.contrib.auth.models.
- In general, AbstractUser is – An abstract base class that implements a fully functional user model with admin-compliant permissions. It is necessary to enter a username and password. Other fields are optional.
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
contact = models.IntegerField(default=None)
degree = models.CharField(max_length=100)
grad_year = models.IntegerField()
specialization = models.CharField(max_length=100)
college_name = models.CharField(max_length=100)
Step 7: Make Migrations
- We will do migrations after building the model, and to do so, we will execute the following commands
python manage.py makemigrations
python manage.py migrate
Step 8: Create Form
- We will develop forms that are used to create fields and add them to the database after creating the templates.
- A username, password, and password confirmation are included on the form by default. We’ll modify it with a few new fields. To do this, we must develop forms.py inside the application.
- Using the current username and password, we import UserCreationForm from django.contrib.auth.forms to create users with no privileges.
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
from django import forms
User = get_user_model()
class LoginForm(forms.Form):
username = forms.CharField(
widget=forms.TextInput(
attrs= {
"class": "forms-control"
}
)
)
password = forms.CharField(
widget=forms.PasswordInput(
attrs={
"class": "forms-control"
}
)
)
class RegistrationForm(UserCreationForm):
email = forms.EmailField()
contact = forms.IntegerField()
degree = forms.CharField(max_length=100)
grad_year = forms.IntegerField()
specialization = forms.CharField(max_length=100)
college_name = forms.CharField(max_length=100)
class Meta:
model = User
fields = ('email', 'contact', 'degree', 'grad_year', 'specialization', 'college_name', 'username', 'password1', 'password2')
Step 9 : Create urls.py
- Then, we’ll add paths to the provided files in urls.py.
- First, we’ll set the default path, which will be in the base directory’s project directory.And by including path, we refer to an app’s URL path.
- Urls.py:(base directory)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('apps.person.urls')),
path('', include('django.contrib.auth.urls')),
]
- Urls.py:
from django.urls import path
from django.contrib.auth.views import LoginView
from . import views
urlpatterns = [
path('register/', views.register, name='register'),
path('login/', views.login_view, name='login'),
path('logout/', views.logout_view, name='logout'),
path('home/', views.homepage, name='home'),
Step 10 : Views.py file
There is a file called views.py inside the app.
- Register view:
We’ll first create a basic registration view.
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate,login,logout
from .forms import RegistrationForm, LoginForm
def register(request):
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
print('inside')
form.save()
return redirect('home')
else:
msg = 'form is not valid'
return render(request, 'registration/Registration.html', {'form': form, 'msg': msg})
else:
msg =''
form = RegistrationForm()
return render(request, 'registration/Registration.html', {'form': form, 'msg': msg})
2.Login view:
def login_view(request):
form = LoginForm(request.POST or None)
if request.method == '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)
return redirect('home')
else:
msg = 'User Invalid'
else:
msg = 'error validating form'
return render(request, 'registration/login.html', {'form': form, 'msg': msg})
return render(request, 'registration/login.html', {'form': form, 'msg': msg})
return render(request, 'registration/login.html', {'form': form})
Step 11 :
1.After a successful login, we want to reroute to the main page. It must be included in our settings.py file. The following needs to be added to the settings.py file’s bottom:
LOGIN_REDIRECT_URL = 'home'
2.A user will now be taken to the main page after logging in. Users will be taken to the login page after logging out. To do so, the following will be included at the end of the settings.py file:
LOGOUT_REDIRECT_URL = 'login'
Step 12 : Create Super User
- In order to read or review the data from the database, we will build a superuser for logging into the admin site.
- We must enter a username, email address, and password in order to create a superuser.
To do that, we’ll issue the following command:
python manage.py createsuperuser
Let’s now launch the programme on localhost: http://127.0.0.1:8000/ We will run the following command to achieve this:
python manage.py runserver