2.4.4.1、Django新建APP(acounts)

$django-admin.py startapp accounts

在oss/accounts修改forms.py(新建)和views.py如下:

注:绿字部分为注释

views.py

################################################################

#coding=utf-8
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login as auth_login ,logout as auth_logout
from django.utils.translation import ugettext_lazy as _
from forms import RegisterForm,LoginForm

def index(request):
    '''首页视图'''
    template_var={"w":_(u"欢迎您,请登录!")}//初始化字典,key=w
    if request.user.is_authenticated()://如果用户登录返回值为1
        template_var["w"]=_(u"欢迎您 %s!")%request.user.username//修改字典key=w对应的值为username
    return render_to_response("accounts/welcome.html",template_var,context_instance=RequestContext(request))//每个视图函数的返回值,具体可参照官方文档,这里表示用accounts/welcome.html模板渲染

def register(request)://注册用户视图
    '''注册视图'''
    template_var={}
    form = RegisterForm()//调用forms.py中RegisterForm() ,初始化form   
    if request.method=="POST"://模板register.html用POST方法提交表单
        form=RegisterForm(request.POST.copy())
        if form.is_valid()://判断表单是否有效
            username=form.cleaned_data["username"]//先判断再赋值
            email=form.cleaned_data["email"]
            password=form.cleaned_data["password"]
            user=User.objects.create_user(username,email,password)//调用Django.auth中创建用户的函数创建用户create_user()
            user.save()//存储添加的用户到数据库
            _login(request,username,password)#注册完毕 直接登陆//调用veiws.py中的登录核心方法
            return HttpResponseRedirect(reverse("index"))//登录成功跳转到urls中对应name=index的视图    
    template_var["form"]=form//把form中存储的user,password,email记录在字典template_var中        
    return render_to_response("accounts/register.html",template_var,context_instance=RequestContext(request))
    
def login_view(request):
    '''登陆视图'''
    template_var={}
    form = LoginForm()    
    if request.method == 'POST':
        form=LoginForm(request.POST.copy())
        if form.is_valid():
            _login(request,form.cleaned_data["username"],form.cleaned_data["password"])
            return HttpResponseRedirect(reverse("index"))
    template_var["form"]=form        
    return render_to_response("accounts/login.html",template_var,context_instance=RequestContext(request))
    
def _login(request,username,password):
    '''登陆核心方法'''
    ret=False
    user=authenticate(username=username,password=password)
    if user:
        if user.is_active:
            auth_login(request,user)//调用Django的login方法(这里是重命名的,参照from XX import XX as xx)
            ret=True
        else:
            messages.add_message(request, messages.INFO, _(u'用户没有激活'))
    else:
        messages.add_message(request, messages.INFO, _(u'用户不存在'))
    return ret//返回登录状态
    
def logout_view(request):
    '''注销视图'''
    auth_logout(request)
    return HttpResponseRedirect(reverse('index'))//注销后跳转到index

forms.py

#coding=utf-8
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

class RegisterForm(forms.Form):
    username=forms.CharField(label=_(u"昵称"),max_length=30,widget=forms.TextInput(attrs={'size': 20,}))
    password=forms.CharField(label=_(u"密码"),max_length=30,widget=forms.PasswordInput(attrs={'size': 20,}))
    email=forms.EmailField(label=_(u"邮件"),max_length=30,widget=forms.TextInput(attrs={'size': 30,}))
    
    def clean_username(self):
        '''验证重复昵称'''
        users = User.objects.filter(username__iexact=self.cleaned_data["username"])
        if not users:
            return self.cleaned_data["username"]
        raise forms.ValidationError(_(u"该昵称已经被使用请使用其他的昵称"))
        
    def clean_email(self):
        '''验证重复email'''
        emails = User.objects.filter(email__iexact=self.cleaned_data["email"])
        if not emails:
            return self.cleaned_data["email"]
        raise forms.ValidationError(_(u"该邮箱已经被使用请使用其他的"))
        
class LoginForm(forms.Form):
    username=forms.CharField(label=_(u"昵称"),max_length=30,widget=forms.TextInput(attrs={'size': 20,}))
    password=forms.CharField(label=_(u"密码"),max_length=30,widget=forms.PasswordInput(attrs={'size': 20,}))

在oss/templates/accounts中添加login.html,register.html和welcome.html 

################################################################

login.html

<html lang="en">
<head>
    <title>Account Login</title>
</head>
<body>
    {% if messages %}
<ul>
    {% for message in messages %}
    <li>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
    <form action="" method="post">
    {% csrf_token %}//防止用户重复非法登录
    <table border="0" cellpadding="0" >
        {{form.as_table}}        
    </table>
    <p> <a href="{%url "register_view"%}">注册</a> <a href="{%url "index"%}">返回首页</a> <input type="submit" value="登录"/></p>
    </form>
</body>
</html>

################################################################

Register.html

<html lang="en">
<head>
    <title>用户注册</title>
</head>
<body><form action="" method="post">{% csrf_token %}
    <table border="0" cellpadding="0" >
        {{form.as_table}}        
    </table>
    <p> <a href="{% url "login_view" %}">登陆</a> <a href="{% url "index" %}">返回首页</a> <input type="submit" value="注册"/></p>
    </form>
</body>
</html>

################################################################

Welcome.html

<html lang="en">
<head>
    <title>Welcome!</title>
</head>
<body>
    <h2>{{w}}</h2>//调用login视图里的字典(key=w)
    <hr/>
{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
{% if user.is_authenticated %}
    <a href="{% url "logout_view" %}">注销</a>
    <a href="{% url "index_oss" %}">返回hrloo_oss主页</a>
{% else %}
    <a href="{% url "login_view" %}">登陆</a>  |
    <a href="{% url "register_view" %}">注册</a>
{% endif %}
</body>
</html>

在oss/urls.py 中添加如下url

url(r'^accounts/login/$', 'oss.accounts.views.login_view', name='login_view'),

url(r'^accounts/logout$', 'oss.accounts.views.logout_view', name='logout_view'),

url(r'^accounts/register$', 'oss.accounts.views.register', name='register_view'),

 

现在启动web服务:python manage.py runserver 10.1.1.145:8000

访问url:http://10.1.1.145:8000/accounts/login 就可以看到登录界面,注册和登出操作访问相应url就可以实现。

posted @ 2014-07-14 10:31  土豆王  阅读(402)  评论(0编辑  收藏  举报