Full width home advertisement

The world of Angular

Basics of Angular 6 - ng6

Post Page Advertisement [Top]

ApplicationDjangoLoginPythonRegistrationUser

Simple Login and User Registration Application using Django

Hi all in this post I'will show you how to create a simple login and user registration application using django. Django is a free and open-source web framework, written in Python, which follows the model-view-template architectural pattern. To create this application I have used django 1.5.0 First open a terminal or console. So lets create a project called 'myapp' using the following command.

django-admin.py startproject myapp
Next we have to create an app in myapp project, lets say the name of the app is 'login'. So to do this first go to the myapp directory using 'cd myapp' then enter the following command.

django-admin.py startapp login
See the following picture.
Simple Login and User Registration Application using Django

And this will create your application. Next I have used a sqlite database for myapp. So now open the settings.py file (myapp > myapp > settings.py) modify the following lines to use a database. And the name of the database file is loginapp.sqlite.

import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': BASE_DIR + '/loginapp.sqlite',  # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '',   # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',   # Set to empty string for default.
    }
}

Now you need to sync the database, to do this go to the terminal and enter the following command. And also create a superuser.

python manage.py syncdb
See the following picture.

Now you need to define the path of your template directory in the settings.py file. To do this add the following line into your TEMPLATE_DIRS directive.

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
      os.path.join(os.path.dirname(__file__), 'templates'),
)
Next you have to add your application name i.e. login into INSTALLED_APPS directive. To do this see the following code.

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
      'login',
)
And also add following lines into your settings.py file. The utility of this two lines is if a user want to access a method that that requires login and the user is not logged in then it will redirect the user to login page.

import django.contrib.auth
django.contrib.auth.LOGIN_URL = '/'
Now create a file called forms.py inside login folder. And paste the following code into that file. This code is used to create the registration form.

#files.py
import re
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

class RegistrationForm(forms.Form):

 username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") })
 email = forms.EmailField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Email address"))
 password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))
 password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)"))

 def clean_username(self):
  try:
      user = User.objects.get(username__iexact=self.cleaned_data['username'])
  except User.DoesNotExist:
      return self.cleaned_data['username']
  raise forms.ValidationError(_("The username already exists. Please try another one."))

 def clean(self):
  if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
   if self.cleaned_data['password1'] != self.cleaned_data['password2']:
    raise forms.ValidationError(_("The two password fields did not match."))
  return self.cleaned_data
Next open the views.py file and paste the following code into there.

#views.py
from login.forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext

@csrf_protect
def register(request):
 if request.method == 'POST':
  form = RegistrationForm(request.POST)
  if form.is_valid():
   user = User.objects.create_user(
   username=form.cleaned_data['username'],
   password=form.cleaned_data['password1'],
   email=form.cleaned_data['email']
   )
   return HttpResponseRedirect('/register/success/')
 else:
  form = RegistrationForm()
 variables = RequestContext(request, {
 'form': form
 })

 return render_to_response(
 'registration/register.html',
 variables,
 )

def register_success(request):
 return render_to_response(
 'registration/success.html',
 )

def logout_page(request):
 logout(request)
 return HttpResponseRedirect('/')

@login_required
def home(request):
 return render_to_response(
 'home.html',
 { 'user': request.user }
 )
Now create a folder called templates inside login folder. Next create a file called base.html inside templates folder and paste the following code in that file. <!--DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"--> <html> <head> <title>Django Login Application | {% block title %}{% endblock %}</title> </head> <body> <h1>{% block head %}{% endblock %}</h1> {% block content %}{% endblock %} </body> </html>
Also create a file called home.html inside templates folder and paste the following code in that file. {% extends "base.html" %} {% block title %}Welcome to Django{% endblock %} {% block head %}Welcome to Django{% endblock %} {% block content %} <p>Welcome {{ user.username }} !!!</p> <a href="/logout/">Logout</a> {% endblock %}
Next create a folder called registration inside templates folder. Create a file called login.html inside the registration folder and paste the following code in that file. {% extends "base.html" %} {% block title %}Login{% endblock %} {% block head %}Login{% endblock %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action=".">{% csrf_token %} <table border="0"> <tr><th><label for="id_username">Username:</label></th><td>{{ form.username }}</td></tr> <tr><th><label for="id_password">Password:</label></th><td>{{ form.password }}</td></tr> </table> <input type="submit" value="Login" /> <input type="hidden" name="next" value="/home" /> </form> <a href="/register">Register</a> {% endblock %}
Next create a file called register.html inside the registration folder and paste the following code in that file. {% extends "base.html" %} {% block title %}User Registration{% endblock %} {% block head %}User Registration{% endblock %} {% block content %} <form method="post" action=".">{% csrf_token %} <table border="0"> {{ form.as_table }} </table> <input type="submit" value="Register" /> </form> <a href="/">Login</a> {% endblock %}
Next create a file called success.html inside the registration folder and paste the following code in that file. {% extends "base.html" %} {% block title %}Registration Successful{% endblock %} {% block head %} Registration Completed Successfully {% endblock %} {% block content %} Thank you for registering. <a href="/">Login</a> {% endblock %}
Finally you need to modify the urls.py file. So open that file and paste the following code in that file.

from django.conf.urls import patterns, include, url
from login.views import *

urlpatterns = patterns('',
 url(r'^$', 'django.contrib.auth.views.login'),
 url(r'^logout/$', logout_page),
 url(r'^accounts/login/$', 'django.contrib.auth.views.login'), # If user is not login it will redirect to login page
 url(r'^register/$', register),
 url(r'^register/success/$', register_success),
 url(r'^home/$', home),
)
Now to run the app go to the terminal and enter the following command.

python manage.py runserver
And to view the application open a browser and go to the following url
http://127.0.0.1:8000/

No comments:

Post a Comment

Bottom Ad [Post Page]