当前位置: 代码迷 >> Web前端 >> 5 Django 1.5.4 User Authentication 用户认证
  详细解决方案

5 Django 1.5.4 User Authentication 用户认证

热度:1226   发布时间:2013-10-31 12:03:52.0
五 Django 1.5.4 User Authentication 用户认证

一.创建drinker app

./manage.py startapp drinker

在INSTALL_APPS添加drinker

用户的Profile模型,django里面是可以自定义的。
通过在settings.py里面指定AUTH_PROFILE_MODULE变量的值就可以了。
AUTH_PROFILE_MODULE = ‘package.model_name’   # profiles.Profile
用户可以使用user.get_profile()来获取自己的profile信息。

在settings.py中添加

AUTH_PROFILE_MODULE='drinker.Drinker'

里面有一个@login_required标签。其作用就是告诉程序,使用这个方法是要求用户登录的。

1.如果用户还没有登录,默认会跳转到‘/accounts/login/’。这个值可以在settings文件中通过LOGIN_URL参数来设定。(后面还会自动加上你请求的url作为登录后跳转的地址,如:/accounts/login/?next=/polls/3/ 登录完成之后,会去请求/poll/3

2.如果用户登录了,那么该方法就可以正常执行

添加

LOGIN_URL='/login/'
LOGIN_REDIRECT_URL='/profile/'
二.修改drinker/models.py

from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User

# Create your models here.
class Drinker(models.Model):
    user        =models.OneToOneField(User)
    birthday    =models.DateField()
    name        =models.CharField(max_length=100)
    def __unicode__(self):
        return self.name
运行
./manage.py syncdb

三.修改drinker/admin.py

from django.contrib import admin
from drinker.models import Drinker

admin.site.register(Drinker)

Meta作用

抽象类

class CommonInfo(models.Model):
  name = models.CharField(max_length = 100)
  age = models.PositiveIntegerField()
  
  class Meta:
      Abstract = True
  
class Student(CommonInfo):
  home_group = models.CharField(max_length = 5)

这样Student就有三个字段:name, age, home_group,所以CommonInfo不可以用作正常的Django model,因为它只是一个抽象基类,它并不生成一个数据库,不能直接实例化或直接保存数据。所以这种抽象基类是非常有用的,它以python的方式提供了一种方法来提取出公共信息,同时仅当子model在创建数据库时才会创建相应的数据。

四.修改drinker/forms.py

最终,如果一个Form实体的数据是合法的,它就会有一个可用的cleaned_data属性。 这是一个包含干净的提交数据的字典。 Django的form框架不但校验数据,它还会把它们转换成相应的Python类型数据,这叫做清理数据。

from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from drinker.models import Drinker

class RegistrationForm(ModelForm):
    username=forms.CharField(label=(u'User Name'))
    email   =forms.EmailField(label=(u'Email Address'))
    password=forms.CharField(label=(u'Password'),widget=forms.PasswordInput(render_value=False))
    password1=forms.CharField(label=(u'Verify Password'),widget=forms.PasswordInput(render_value=False))

    class Meta:
        model=Drinker
        exclude=('user',)
    def clean_username(self):
        username=self.cleaned_data['username']
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError("That username is already taken,please select another.")
    def clean(self):
        if self.cleaned_data['password'] != self.cleaned_data['password1']:
                raise forms.ValidationError("The passwords did not match. Please try again.")
        return self.cleaned_data
class LoginForm(forms.Form):
    username    =forms.CharField(label=(u'User Name'))
    password    =forms.CharField(label=(u'Password'),widget=forms.PasswordInput(render_value=False))

五.修改drinker/views.py

from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from drinker.forms import RegistrationForm,LoginForm
from drinker.models import Drinker
from django.contrib.auth import authenticate,login,logout

def DrinkerRegistration(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/profile/')
    if request.method == 'POST':
        form =RegistrationForm(request.POST)
        if form.is_valid():
            user =User.objects.create_user(username=form.cleaned_data['username'],email=form.cleaned_data['email'],password=form.cleaned_data['password'])
            user.save()
            drinker=Drinker(user=user,name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])
            drinker.save()
            return HttpResponseRedirect('/profile/')
        else:
            return render_to_response('register.html',{'form':form},context_instance=RequestContext(request))
    else:
        form =RegistrationForm()
        context={'form':form}
        return render_to_response('register.html',context,context_instance=RequestContext(request))
@login_required
def Profile(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/')
    drinker=request.user.get_profile
    context={'drinker':drinker}
    return render_to_response('profile.html',context,context_instance=RequestContext(request))
def LoginRequest(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/profile/')
    if request.method == 'POST':
        form=LoginForm(request.POST)
        if form.is_valid():
            username=form.cleaned_data['username']
            password=form.cleaned_data['password']
            drinker=authenticate(username=username,password=password)
            if drinker is not None:
                login(request,drinker)
                return HttpResponseRedirect('/profile/')
            else:
                return render_to_response('login.html',{'form':form},context_instance=RequestContext(request))
        else:
            return render_to_response('login.html',{'form':form},context_instance=RequestContext(request))
    else:
        form=LoginForm()
        context={'form':form}
        return render_to_response('login.html',context,context_instance=RequestContext(request))
def LogoutRequest(request):
    logout(request)
    return HttpResponseRedirect('/')

Django的User对象提供了一系列的属性和方法,其中password存储的是加密后的密码,is_staff记录用户是否有管理员权限,其他的属性可以参考官方文档。同时django.contrib.auth模块中提供了authenticate()、login()、logout()等函数,分别实现认证、登录、登出等功能。Django还为我们提供了内置的处理login、logout的view函数,但是因为其提供的行为与我们这里要的不一样,所以还需要自己实现view函数。

六.修改templates/register.html

{% extends "base.html" %}
{% block extrahead %}
    <script src="http://libs.baidu.com/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://libs.baidu.com/jqueryui/1.8.18/jquery-ui.min.js" type="text/javascript"></script>
    <script>
     $(function() {
             $( "#id_birthday" ).datepicker();
             });
    </script>
{% endblock %}
{% block content %}
<form action="" method="post">{% csrf_token %}
    {% if form.errors %}
    <p> Please correct the following fields: </p>
    {% endif %}
    <div class="register_div">
        {% if form.username.errors %} <p class="error"> {{ form.username.errors }} </p> {% endif %}
        <p><label for="username" {% if form.username.errors %} class="error" {% endif %}>Username:</label></p>
        <p>{{ form.username }}</p>
    </div>
    <div class="register_div">
        {% if form.email.errors %} <p class="error"> {{ form.email.errors }} </p> {% endif %}
        <p><label for="email" {% if form.email.errors %} class="error" {% endif %}>Email:</label></p>
        <p>{{ form.email}}</p>
    </div>
    <div class="register_div">
        {% if form.password.errors %} <p class="error"> {{ form.password.errors }} </p> {% endif %}
        <p><label for="password" {% if form.password.errors %} class="error" {% endif %}>Password:</label></p>
        <p>{{ form.password}}</p>
    </div>
    <div class="register_div">
        {% if form.password1.errors %} <p class="error"> {{ form.password1.errors }} </p> {% endif %}
        <p><label for="password1" {% if form.password1.errors %} class="error" {% endif %}>Verify Password:</label></p>
        <p>{{ form.password1}}</p>
    </div>
    <div class="register_div">
        {% if form.birthday.errors %} <p class="error"> {{ form.birthday.errors }} </p> {% endif %}
        <p><label for="birthday" {% if form.birthday.errors %} class="error" {% endif %}>Birthday:</label></p>
        <p>{{ form.birthday}}</p>
    </div>
    <div class="register_div">
        {% if form.name.errors %} <p class="error"> {{ form.name.errors }} </p> {% endif %}
        <p><label for="name" {% if form.name.errors %} class="error" {% endif %}>Name:</label></p>
        <p>{{ form.name}}</p>
    </div>
    <p><input type="submit" alt="register"></p>
</form>
{% endblock %}

templates/login.html

{% extends "base.html" %}
{% block content %}
<form action="" method="post">{% csrf_token %}
    {% if form.errors %}
    <p> Please correct the following fields: </p>
    {% endif %}
    <div class="register_div">
        {% if form.username.errors %} <p class="error"> {{ form.username.errors }} </p> {% endif %}
        <p><label for="username" {% if form.username.errors %} class="error" {% endif %}>Username:</label></p>
        <p>{{ form.username }}</p>
    </div>
    <div class="register_div">
        {% if form.password.errors %} <p class="error"> {{ form.password.errors }} </p> {% endif %}
        <p><label for="password" {% if form.password.errors %} class="error" {% endif %}>Password:</label></p>
        <p>{{ form.password}}</p>
    </div>
    <p><input type="submit" alt="register"></p>
</form>
{% endblock %}

templates/base.html

<html>
<head>
    <link rel="stylesheet" type="text/css" href="/static/css/video1.css" />
    {% block extrahead %}
    {% endblock %}
</head>
<body>
<div id="pageContainer">
    <div id="nav_top_right">
        {% if user.is_authenticated %}
        <p><a href="/logout/">Logout</a></p>
        {% else %}
        <p><a href="/login/">login</a></p>
        {% endif %}
    </div>
    {% block content %}

    {% endblock %}
</div>
</body>
</html>

templates/profile.html

{% extends "base.html" %}
{% block content %}
<p>Name: {{ drinker.name }}</p>
<p>Birthday: {{ drinker.birthday }}</p>
{% endblock %}

urls.py中添加

    
    (r'^register/$','drinker.views.DrinkerRegistration'),
    (r'^login/$','drinker.views.LoginRequest'),
    (r'^logout/$','drinker.views.LogoutRequest'), 
    (r'^profile/$','drinker.views.Profile'), 

  相关解决方案