Wednesday, 1 March 2017

Django full login, logout, registration Forms

Here is the examples of Django full login, logout, registration Forms .


Start a project called  myproject :

Now

myprojec/urls.py:

from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from views import *
from django.views.generic.base import TemplateView


urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
    url(r'^register_page/$', register_page, name='register_page'),
    url(r'^register_success/$', register_success, name='register_success'),
    url(r'^accounts/profile/$', index, name='index'),
    url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'),
   
]


 myproject/views.py:

from django.shortcuts import render
from django.shortcuts import render_to_response,redirect,get_object_or_404
from django.http import HttpResponse,Http404,HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import login,authenticate
from django.contrib.auth.forms import UserCreationForm
from mysite.forms import  *

def register_success(request):
        return render_to_response('registration_success.html')

def register_page(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()
        return render_to_response('registration/register.html',RequestContext(request,{'form':form}))

@login_required
def index(request):
        names=Name.objects.all()
        return redirect('home')

def register_success(request):
        return render_to_response('register_success.html')

myproject/forms.py:


import re
from django import forms
from django.contrib.auth.models import User

class RegistrationForm(forms.Form):
        username=forms.CharField(label=u'Username',max_length=30)
        email=forms.EmailField(label=u'Email')
        password1=forms.CharField(label=u'Password',widget=forms.PasswordInput())
        password2=forms.CharField(label=u'Password(Again)',widget=forms.PasswordInput())

        def clean_password2(self):
                if 'password1' in self.cleaned_data:
                        password1=self.cleaned_data['password1']
                        password2=self.cleaned_data['password2']
                        if password1==password2:
                                return password2
                raise forms.ValidationError('Password do not matched.')

        def clean_username(self):
                username=self.cleaned_data['username']
                if not re.search(r'^\w+$',username):
                        raise forms.ValidationError('Username only contals alpha numaric and underscore')
                try:
                        User.objects.get(username=username)
                except User.DoesNotExist:
                        return username
                raise forms.ValidationError('Username already taken')

Create a myproject/Template folder and put the bellow files :


home.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Home Page</title>
</head>
<body>
    <h1>Home Page</h1>
    {% if user.is_authenticated %}
      Hi {{ user.username }}!      <a href="{% url 'logout' %}">logout</a>
    {% else %}
<h2><a href="{% url 'login' %}">login</a> Or <a href="{% url 'register_page' %}">Register Yourself</a></h2>
{%endif%}
</body>
</html>


registration_success.html:


<!DOCTYPE html>
<html>
<head>
        <title> Registration Successful</title>
</head>
<body>
<h1>Registration Completed Successfully.</h1>
Thanks for registraring. Your information has been saved to database. Now you can
either <a href="/login/">login</a> or go back to the <a href="/">main</a> page.
</body>
</html>



In the myproject/Template/ create a folder called registration: 


Put bellow files there :

register.html:

<!DOCTYPE html>
<html>
<head>
        <title> Create Account</title>
</head>
<body>
<h1>User Registration Or <a href="{% url 'login' %}">Log in</a> </h1>
<form  action="." method="post">{%csrf_token%}
{{form.as_p}}
        <input type="submit" value="register"/>
</form>

</body>
</html>



Bellow are some SS:









You can add me  in Facebook here.







No comments:

Post a Comment

Popular Posts