Monday, 4 August 2014

how to create or register,login and manage user in django

Standard

you prepare a cocktail but no one have to drink so how to know your cocktail best or not

so today i will write how you manage,login,logout and register user

User registration and account management are universal features found in every
web application. Users need to identify themselves to the application before they can post and share content with other users. User accounts are also required for online discussions and friend networks, among many other uses. so i will focus on building features related to account registration and management, and
taking advantage of the user authentication system that comes with Django.

so now we will follow some common rules like

• Creating a login page.
• Enabling logout functionality.
• Creating a registration form.
• Enabling users to update their account information.

when i will developing the above items, then i use two important Django features:

• Template inheritance.
• The forms library.



Session Authentication

open your setting.py file in editor and follow the bellow code if any line is missing then write:

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'store.app',
)

next set check SITE_ID exist or not if not then write a variable SITE_ID=1 and run bellow command in terminal

$python manage.py syncdb

Before we start using the authentication system, let's have a quick look at the features:

  • Users: A User data model with fields commonly required by web applications.
  • Permissions: Yes/No flags that indicate whether a user may access a certain feature or not.
  • Groups: A data model for grouping more than one user together and applying the same set of permissions to them.
  • Messages: Provides the functionality for displaying information and error messages to the user.

Creating the Login Page

Those who have worked on programming a session management system in a low-level web framework (such as PHP and its library) will know that this task is not so easy. There are many things that could go wrong in a task, and a little mistake may open the system to security problems. However, Django developers have carefully implemented a session management system for us, and activating it requires certain views to the user but we don't have to worry about managing user sessions or checking passwords. All of these are already implemented and ready to be used.

let's start the login page, first of all, you need to add a new URL entry to urls.py. Open the file in your editor and change it so that the URL table looks like the following:

urlpatterns = patterns('',(r'^$', main_page),(r'^user/(\w+)/$', user_page),(r'^login/$', 'django.contrib.auth.views.login'),)

The next step is creating a template for the view. Make a folder named registration within the templates folder, and create a file called login.html in it and enter the following code into login.html:

 <html>
<head>
<title>Django Store - User Login</title>

</head>
<body>
<h1>User Login</h1>
{% if form.has_errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action=".">
<p><label for="id_username">Username:</label>
{{ form.username }}</p>
<p><label for="id_password">Password:</label>
{{ form.password }}</p>
<input type="hidden" name="next" value="/" />
<input type="submit" value="login" />

{% csrf_token %}
</form>
</body>
</html>


Ready to try the login view! Run the development server and navigate to http://127.0.0.1:8000/login/. You will be see the following login page:

after login page will redirect to home page if your want to redirect to other page then set url in nest input field in login form
Now that i can log in, it is a good idea to make the main page indicate whether you are logged in or not. So let's write its view and template. First open templates/main_page.html and replace its contents with the following:

<html>
<head>
<title>Django Store</title>
</head>
<body>
<h1>Welcome to Django Store</h1>
{% if user.username %}
<p>Welcome {{ user.username }}!
Here you can show your content!</p><br/>

<a href="logout">logout<>
{% else %}
<p>Welcome anonymous user!
You need to <a href="/login/">login</a></p>
{% endif %}
</body>
</html>


The template now checks whether a variable called user.username is set or not. If it is, the logged-in user is greeted. Otherwise, a link to the login page is displayed. The template assumes that the user variable is passed to it (the user variable is a Django object that we will learn about shortly), so let's modify the main page view to this. Open app/views.py and change the view as follows:

def main_page(request):
    template = get_template('main_page.html')
    variables = Context({ 'user': request.user })
    output = template.render(variables)
    return HttpResponse(output)


now run your server you will see home page

The user object available at request.user is the same type of User object as we have dealt with before. We are already familiar with its data fields, so let's learn about some of its methods:

  • is_authenticated() returns a Boolean value indicating whether the user is
  • get_full_name() returns the first name and the last name of the user, with a
  • email_user(subject, message, from_email=None) sends an email to logged in or not.
  • set_password(raw_password) sets the user password to the passed value.
  • check_password(raw_password) returns a Boolean value indicating whether the passed password matches the user password.

Enabling Logout Functionality

now i have login page. next step is a way to user will logout, when user will hit /logout url i will log them out and redirect to main_page it's so easy

first create a new view in app/views.py:

from django.http import HttpResponseRedirect
from django.contrib.auth import logout
def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/')

Now we need to add a URL entry for this view. Open urls.py and create an entry as follows:

urlpatterns = patterns('',
(r'^$', main_page),
(r'^user/(\w+)/$', user_page),
(r'^login/$', 'django.contrib.auth.views.login'),
(r'^logout/$', logout_page),
)


and add logout link in main page and reload page click on logout link you will logout

Improving Template Structure

now we will develop a layout for our template
Let's apply this feature to our project. Create a file called base.html in templates with the following content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Django store | {% block title %}{% endblock %}</title>
</head>
<body>
<div id="nav">
<a href="/">home</a> |
{% if user.is_authenticated %}
welcome {{ user.username }}
(<a href="/logout">logout</a>)
{% else %}
<a href="/login/">login</a> |
<a href="/register/">register</a>
{% endif %}
</div>
<h1>{% block head %}{% endblock %}</h1>
{% block content %}{% endblock %}
</body>
</html>
now edit templates/main_page.html and replace its content with the following:

{%extends "base.html" %}
{%block title %}Welcome to Django store{% endblock %}
{%block head %}Welcome to Django store{% endblock %}
{%block content %}
{% if user.username %}
<p>Welcome {{ user.username }}!Here your page content</p>
{% else %}
<p>Welcome anonymous user!
You need to login</p><br/>
{% endif %}
{% endblock %}


Finally, let's see how to convert templates/registration/login.html:
{%extends "base.html" %}
{%block title %}User Login{% endblock %}
{%block head %}User Login{% endblock %}
{%block content %}
{% if form.has_errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action=".">
<p><label for="id_username">Username:</label>
{{ form.username }}</p>
<p><label for="id_password">Password:</label>
{{ form.password }}</p>
<input type="submit" value="login" />
<input type="hidden" name="next" value="/" />
{% csrf_token %}
</form>
{% endblock %}


replace bellow code to main_page in views.py

from django.template import RequestContext
from django.shortcuts import render_to_response

def main_page(request):
    return render_to_response('home.html', RequestContext(request))

User Registration

The first user account was added to the database during the creation of our Django project. However, site visitors also need a method to create accounts on the site. User registration is a basic feature. We will create a user registration form in this section, and in the process we will also learn about the Django library that handles form generation and processing.

Django Forms

Creating, validating and processing forms is an all too common task. Web applications receive input and collect data from users by means of web forms. So naturally Django comes with its own library to handle these tasks. To avoid having to go through a lot of code updates when the name changes, it is recommended to import the package like this:

from django import forms
The Django forms library handles 3 common tasks:
  • HTML form generation.
  • Server-side validation of user input.
  • HTML form redisplay in case of input errors.
i will tell about the forms library by creating a user registration form:

Designing the User Registration Form

first of all create a new file in the app application folder and call it forms.py. Then open the file in your code editor and enter the following code:

 from django import forms
class RegistrationForm(forms.Form):
    username = forms.CharField(label='Username', max_length=30)
    email = forms.EmailField(label='Email')
    password1 = forms.CharField(label='Password',

                          widget=forms.PasswordInput())
    password2 = forms.CharField(label='Password (Again)',

                        widget=forms.PasswordInput())

we defined the fields that this form contains. There are many field types in the forms package. There are several parameters, listed below, which can be passed to the constructor of any field type. Some specialized field types can take other parameters in addition to these ones:
  • label: The label of the field when HTML code is generated.
  • required: Whether the user must enter a value or not. It is set to true by default. To change it, pass required=False to the constructor.
  • widget: This parameter lets you control how the field is rendered in HTML. We used it above to make the CharField of the password become a password input field.
  • help_text: A description of the field. Will be displayed when the form is rendered.
bellow screen shot is basic configuration of form check

Now that you are comfortable with forms.Form instances, we need to improve data validation for our form. The form in its current state detects missing fields and invalid email addresses but we still need to do the following:

• Prevent the user from entering an invalid username or a username that's
   already in use.
• Make sure that the two password fields match.

Let's start with password validation because it's simpler. Open app/forms.py and append the following method to the RegistrationForm class:

    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('Passwords do not match.')


With password validation done, we will move to username validation. Add the following import statements at the beginning of app/forms.py:

import re
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist


re is the regular expressions library. We will need it to make sure that the username doesn't contain invalid characters. We also import the User data model to check whether the entered username already exists or not. Lastly, we import ObjectDoesNotExist which is the type of exception raised if the data object is not found.
Next, append the following method to RegistrationForm:

    def clean_username(self):
        username = self.cleaned_data['username']
        if not re.search(r'^\w+$', username):
            raise forms.ValidationError('Username can only contain 

                                alphanumeric characters and the underscore.')
        try:
            User.objects.get(username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError('Username is already taken.')


We now have the registration form ready, but we still need a view and a template. Let's start with the view. Open app/views.py and insert the following code:

from app.forms import *

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

This view does two things:
  • If it's requested via the POST method, the user has submitted registration information. In this case, the view processes user input, and redirects to the main page if everything goes well.
  • Otherwise, the page generates HTML code for the registration form, and renders a template called registration/register.html.
Now we will move to the registration page template. Create a new file called templates/registration/register.html, and add the following code to it:

{% extends "base.html" %}
{% block title %}User Registration{% endblock %}
{% block head %}User Registration{% endblock %}
{% block content %}
<form method="post" action=".">
{{ form.as_p }}
<input type="submit" value="register" />
{% csrf_token %}
</form>
{% endblock %}


Before we can test the registration view, we need to add a URL entry for it. Open urls.py and add the following line to the URL table:

(r'^register/$', register_page),

now start server and hit url in browser or add register link:

http://localhost:8000/register

all screen shot like

Home page

registration page

login page

after login page



now you have prepared cocktail. just drink or give to other

enjoy