Django:登录、注册、退出

创建项目:

一、创建项目

django-admin startproject form_test

二、创建应用

1、cd form_test
2、sudo ./manage.py startapp form_app

三、配置应用

1、vim setting.py
2、在INSTALLED_APPS添加刚创建的应用(’form_app’)

四、创建url(form_test/urls.py)

#form_test/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'form_test.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'form_app.views.login',name='login'),
    url(r'^login/$', 'form_app.views.login',name='login'),
    url(r'^regist/$', 'form_app.views.regist',name='regist'),
    url(r'^index/$', 'form_app.views.index',name='index'),
    url(r'^logout/$', 'form_app.views.logout',name='logout'),
    url(r'^share/$', 'form_app.views.share',name='share'),
)

 

五、创建数据库对象(form_app/models.py)

from django.db import models

# Create your models here.
class User(models.Model):
    username = models.CharField(max_length=50)
    password = models.CharField(max_length=50)

    def __unicode__(self):
        return self.username

 

六、编写视图(/form_app/views.py)

#coding:utf-8
from django.shortcuts import render,render_to_response
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from models import User
# Create your views here.

#表单
class UserForm(forms.Form):
    username = forms.CharField(label='用户名',max_length=100)
    password = forms.CharField(label='密__码',widget=forms.PasswordInput())

def regist(req):
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            #获取表单数据
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            #添加到数据库
            #User.objects.get_or_create(username = username,password = password)
            registAdd = User.objects.get_or_create(username = username,password = password)[1]
            if registAdd == False:
                #return HttpResponseRedirect('/share/')
                return render_to_response('share.html',{'registAdd':registAdd,'username':username})
            else:
                return render_to_response('share.html',{'registAdd':registAdd})

    else:
        uf = UserForm()
    return render_to_response('regist.html',{'uf':uf},context_instance=RequestContext(req))

def login(req):
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            #对比提交的数据与数据库中的数据
            user = User.objects.filter(username__exact = username,password__exact = password)
            if user:
                #比较成功,跳转index
                response = HttpResponseRedirect('/index/')
                #将username写入浏览器cookie,失效时间为3600
                response.set_cookie('username',username,3600)
                return response
            else:
                return HttpResponseRedirect('/login/')
    else:
        uf = UserForm()
    return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))
#登录成功
def index(req):
    username = req.COOKIES.get('username','')
    return render_to_response('index.html',{'username':username})
#退出登录

def logout(req):
    response = HttpResponse('logout!!!')
    #清除cookie里保存的username
    response.delete_cookie('username')
    return response

def share(req):
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']

            return render_to_response('share.html',{'username':username})
    else:
        uf = UserForm()
    return render_to_response('share.html',{'uf':uf})

 

 

 

 

七、创建templates(form_app/templates)

1、cd templates
2、sudo touch share.html、regist.html、login.html、logout.html、index.html
3、share.html

{{registAdd}} 
<br>
==================
<br>
{% if  username %}
注册失败{{username}}已存在
<a href="http://127.0.0.1:8000/regist">注册</a>
{% else %}
注册成功!
<a href="http://127.0.0.1:8000/login">登录</a>
{% endif %}

 

 

4、regist.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Regist</title>
</head>
<body>
<h1>注册页面</h1>
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{uf.as_p}} 
    <input type="submit" value="ok"></input>
</form>
<a href="http://127.0.0.1:8000/login">登录</a>
</body>
</html>

 

 

5、login.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Login</title>
</head>
<body>
<h1>登录页面</h1>
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{uf.as_p}} 
    <input type="submit" value="ok"></input>
</form>
<a href="http://127.0.0.1:8000/regist">注册</a>
</body>
</html>

 

 

6、index.html

<!DOCTYPE html>
<html>
<head>
    <title>index</title>
</head>
<body>
<h1>Welcome {{ username }}!</h1>
<br>
<a href="http://127.0.0.1:8000/logout">退出</a>
</body>
</html>
posted @ 2018-03-14 16:31  努力乄小白  阅读(786)  评论(0编辑  收藏  举报