Python - Simple Registration & Login Form With Django

In this tutorial we will create a Simple Registration & Login Form With Django. Django is a free and open source web application framework, written in Python. A web framework is a set of components that helps you to develop websites faster and easier. Django makes developers life convenient and productive framework to all. So let's now do the coding...

Getting Started

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/. After Python IDLE's is installed, open the command prompt then type "pip install Django", and hit enter. tut1 Wait for the django to be downloaded and installed at the same time. Then After that type "python -m django version" and hit enter to check if django is installed and what version of django is. tut2

Creating the App

After setting django we will now create the web app for the web server. First create a new folder named "Django RegistrationAndLogin", then cd to a newly created folder, then type "django-admin startproject website" and hit enter. A new folder will be created on the directory named 'website'. tut3

Running The Server

After creating a project, cd to the newly created directory, then type "manage.py runserver" and hit enter to start the server running. The "manage.py" is a command of django-admin that utilize the administrative tasks of python web framework. Here is the image of python web server: tut4Note: Type '127.0.0.1:8000' in the url browser to view the server. When there is code changes in the server just (ctrl + C) to command prompt to stop the server from running, then start again to avoid errors.

Creating The Website

This time will now create the web app to display the web models. First locate the directory of the app via command prompt cd, then type "manage.py startapp web" and hit enter. A new directory will be create inside the app named "web". tut5

Setting up The URL

This time will now create a url address to connect the app from the server. First Go to website directory, then open urls via Python IDLE's or any text editor. Then import "include" module beside the url module and import additional module to make a redirect url to your site "from . import views". After that copy/paste the code below inside the urlpatterns.
  1. url(r'^$', views.index_redirect, name='index_redirect'),
  2. url(r'^web/', include('web.urls')),
It will be look like this:
  1. from django.conf.urls import include, url
  2. from django.contrib import admin
  3. from . import views
  4.  
  5. urlpatterns = [
  6. url(r'^$', views.index_redirect, name='index_redirect'),
  7. url(r'^web/', include('web.urls')),
  8. url(r'^admin/', admin.site.urls),
  9. ]
Then after that create a view that will catch the redirect url. To do that create a file "views.py" then copy/paste the code below and save it as "views.py".
  1. from django.shortcuts import redirect
  2. from . import views
  3.  
  4. def index_redirect(request):
  5. return redirect('/web/')

Creating The Path For The Pages

Now that we set the connect we will now create a path for the web pages. All you have to do first is to go to web directory, then copy/paste the code below and save it inside "web" directory named 'urls.py' The file name must be urls.py or else there will be an error in the code.
  1. from django.conf.urls import url
  2. from . import views
  3.  
  4. urlpatterns = [
  5. url(r'^$', views.index, name='index'),
  6. url(r'^login/$', views.login, name='login'),
  7. url(r'^home/$', views.home, name='home'),
  8. ]

Creating A Static Folder

This time we will create a directory that store an external file. First go to the web directory then create a directory called "static", after that create a sub directory called "web". You'll notice that it is the same as your main app directory name, to assure the absolute link. This is where you import the css, js, etc directory.

Creating The Views

The views contains the interface of the website. This is where you assign the html code for rendering it to django framework and contains a methods that call a specific functions. To do that first open the views.py, the copy/paste the code below.
  1. from django.shortcuts import render, redirect, HttpResponseRedirect
  2. from .models import Member
  3. # Create your views here.
  4.  
  5. def index(request):
  6. if request.method == 'POST':
  7. member = Member(username=request.POST['username'], password=request.POST['password'], firstname=request.POST['firstname'], lastname=request.POST['lastname'])
  8. member.save()
  9. return redirect('/')
  10. else:
  11. return render(request, 'web/index.html')
  12.  
  13. def login(request):
  14. return render(request, 'web/login.html')
  15.  
  16. def home(request):
  17. if request.method == 'POST':
  18. if Member.objects.filter(username=request.POST['username'], password=request.POST['password']).exists():
  19. member = Member.objects.get(username=request.POST['username'], password=request.POST['password'])
  20. return render(request, 'web/home.html', {'member': member})
  21. else:
  22. context = {'msg': 'Invalid username or password'}
  23. return render(request, 'web/login.html', context)

Creating The Models

Now that we're done with the views we will then create a models. Models is module that will store the database information to django. To do that locate and go to web directory, then open the "models.py" after that copy/paste the code.
  1. from django.db import models
  2.  
  3. # Create your models here.
  4.  
  5. class Member(models.Model):
  6. firstname=models.CharField(max_length=30)
  7. lastname=models.CharField(max_length=30)
  8. username=models.CharField(max_length=30)
  9. password=models.CharField(max_length=12)
  10.  
  11. def __str__(self):
  12. return self.firstname + " " + self.lastname

Registering The App To The Server

Now that we created the interface we will now then register the app to the server. To do that go to the website directory, then open "settings.py" via Python IDLE's or any text editor. Then copy/paste this script inside the INSTALLED_APP variables 'web'. It will be like this:
  1. INSTALLED_APPS = [
  2. 'web',
  3. 'django.contrib.admin',
  4. 'django.contrib.auth',
  5. 'django.contrib.contenttypes',
  6. 'django.contrib.sessions',
  7. 'django.contrib.messages',
  8. 'django.contrib.staticfiles',
  9. ]

Creating The Mark up Language

Now we will create the html interface for the django framework. First go to web directory, then create a directory called "templates" and create a sub directory on it called web. base.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5. {% load static %}
  6. <link rel="stylesheet" type="text/css" href="{% static 'web/css/bootstrap.css' %}" />
  7. </head>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11. </div>
  12. </nav>
  13. <div class="col-md-3"></div>
  14. <div class="col-md-6 well">
  15. <h3 class="text-primary">Python - Simple Registration & Login Form</h3>
  16. <hr style="border-top:1px dotted #000;"/>
  17. {% block body %}
  18. {% endblock %}
  19. </div>
  20. </body>
  21. </html>
Save it as "base.html" inside the web directory "sub directory of templates". index.html
  1. {% extends 'web/base.html' %}
  2. {% block body %}
  3. <form method="POST">
  4. {% csrf_token %}
  5. <div class="col-md-2">
  6. <a href="{% url 'login' %}">Login</a>
  7. </div>
  8. <div class="col-md-8">
  9. <div class="form-group">
  10. <label for="username">Username</label>
  11. <input type="text" name="username" class="form-control" required="required">
  12. </div>
  13. <div class="form-group">
  14. <label for="password">Password</label>
  15. <input type="password" name="password" class="form-control" required="required"/>
  16. </div>
  17. <div class="form-group">
  18. <label for="firstname">Firstname</label>
  19. <input type="text" name="firstname" class="form-control" required="required"/>
  20. </div>
  21. <div class="form-group">
  22. <label for="lastname">Lastname</label>
  23. <input type="text" name="lastname" class="form-control" required="required"/>
  24. </div>
  25. <br />
  26. <div class="form-group">
  27. <button type="submit" class="btn btn-primary form-control"><span class="glyphicon glyphicon-save"></span> Submit</button>
  28. </div>
  29. </div>
  30. </form>
  31. {% endblock %}
Save it as "index.html" inside the web directory "sub directory of templates". login.html
  1. {% extends 'web/base.html' %}
  2. {% block body %}
  3. <form method="POST" action="{% url 'home' %}">
  4. {% csrf_token %}
  5. <div class="col-md-2">
  6. <a href="{% url 'index' %}">Signup</a>
  7. </div>
  8. <div class="col-md-8">
  9. <div class="form-group">
  10. <label for="username">Username</label>
  11. <input type="text" name="username" class="form-control" required="required"/>
  12. </div>
  13. <div class="form-group">
  14. <label for="password">Password</label>
  15. <input type="password" name="password" class="form-control" required="required"/>
  16. </div>
  17. <center><label class="text-danger">{{ msg }}</label></center>
  18. <br />
  19. <div class="form-group">
  20. <button class="btn btn-primary form-control"><span class="glyphicon glyphicon-log-in"></span> Login</button>
  21. </div>
  22. </div>
  23. </form>
  24.  
  25. {% endblock %}
Save it as "login.html" inside the web directory "sub directory of templates". home.html
  1. {% extends 'web/base.html' %}
  2. {% block body %}
  3. <h2>Welcome</h2>
  4. {{ member.firstname }}
  5. {% endblock %}
Save it as "home.html" inside the web directory "sub directory of templates".

Migrating The App To The Server

Now that we done in setting up all the necessary needed, we will now then make a migration and migrate the app to the server at the same time. To do that open the command prompt then cd to the "website" directory, then type "manage.py makemigrations" and hit enter. After that type again "manage.py migrate" then hit enter. tut6 Now try to run the server again, and see if all things are done. There you have it we successfully created a Simple Registration & Login Form With Django. I hope that this simple tutorial help you for what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Tags

Comments

Add new comment