Django1.7中注册、登陆、以及cookie的使用

发布时间:2020-04-01 05:35:42 作者:飞侠119
来源:网络 阅读:774

创建项目与应用

#django-admin.pystartproject myadmin

#cd myadmin

#python manage.py startapp online

Django1.7中注册、登陆、以及cookie的使用

打开myadmin/myadmin/settings.py文件,将应用添加进去:

Django1.7中注册、登陆、以及cookie的使用

设计数据库  

打开myadmin/online/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

下面进行数据库的同步:

# python manage.py syncdb

Operations toperform:

  Apply all migrations: admin, contenttypes,auth, sessions

Runningmigrations:

  Applying contenttypes.0001_initial... OK

  Applying auth.0001_initial... OK

  Applying admin.0001_initial... OK

  Applying sessions.0001_initial... OK

 

You haveinstalled Django's auth system, and don't have any superusers defined.

Would you liketo create one now? (yes/no): yes

Username (leaveblank to use 'root'): root

Email address: 135xxx@qq.com

Password:

Password(again):

Superusercreated successfully.

[root@bogonmyadmin]# python manage.py makemigrations

Migrations for'online':

  0001_initial.py:

    - Create model User

[root@bogonmyadmin]# python manage.py migrate

Operations toperform:

  Apply all migrations: admin, contenttypes,sessions, auth, online

Runningmigrations:

  Applying online.0001_initial... OK

配置URL

打开myadmin/myadmin/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite5.views.home', name='home'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^online/', include('online.urls')),
)

mysite5/online/目录下创建urls.py文件:

from django.conf.urls import patterns, url
from online import views
urlpatterns = patterns('',
    url(r'^$', views.login, name='login'),
    url(r'^login/$',views.login,name = 'login'),
    url(r'^regist/$',views.regist,name = 'regist'),
    url(r'^index/$',views.index,name = 'index'),
    url(r'^logout/$',views.logout,name = 'logout'),
)

创建视图  

打开myadmin/online/views.py 文件:

#coding=utf-8
from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from django import forms
from models import User
 
#表单
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.create(username= username,password=password)
            return HttpResponse('regist success!!')
    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('/online/index/')
                #将username写入浏览器cookie,失效时间为3600
                response.set_cookie('username',username,3600)
                return response
            else:
                #比较失败,还在login
                return HttpResponseRedirect('/online/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

这里实现了所有注册,登陆逻辑,中间用到cookie创建,读取,删除操作等。

创建模板

先在mysite5/online/目录下创建templates目录,接着在mysite5/online/templates/目录下创建regist.html 文件:

<?xmlversion="1.0" encoding="UTF-8"?>

<!DOCTYPEhtml PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml" xml:lang="en"lang="en">

<head>

    <metahttp-equiv="Content-Type" content="text/html;charset=UTF-8" />

    <title>注册</title>

</head>

 

<body>

<h2>注册页面:</h2>

<form method= 'post' enctype="multipart/form-data">

    {% csrf_token %}

    `uf`.`as_p`

    <input type="submit" value ="ok" />

</form>

<br>

<ahref="http://127.0.0.1:8000/online/login/">登陆</a>

</body>

</html>

myadmin/online/templates/目录下创建login.html 文件:

<?xmlversion="1.0" encoding="UTF-8"?>

<!DOCTYPEhtml PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml" xml:lang="en"lang="en">

<head>

    <metahttp-equiv="Content-Type" content="text/html;charset=UTF-8" />

    <title>登陆</title>

</head>

 

<body>

<h2>登陆页面:</h2>

<form method= 'post' enctype="multipart/form-data">

    {% csrf_token %}

    `uf`.`as_p`

    <input type="submit" value ="ok" />

</form>

<br>

<ahref="http://127.0.0.1:8000/online/regist/">注册</a>

</body>

</html>

myadmin/online/templates/目录下创建index.html 文件:

<?xmlversion="1.0" encoding="UTF-8"?>

<!DOCTYPEhtml PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml" xml:lang="en"lang="en">

<head>

    <metahttp-equiv="Content-Type" content="text/html;charset=UTF-8" />

    <title></title>

</head>

 

<body>

<h2>welcome `username` !</h2>

<br>

<ahref="http://127.0.0.1:8000/online/logout/">退出</a>

</body>

</html>

使用功能

注册


Django1.7中注册、登陆、以及cookie的使用

登陆

Django1.7中注册、登陆、以及cookie的使用



推荐阅读:
  1. Django 之 Cookie的使用(判断是否已登陆)
  2. 教你使用JavaWeb实现无处不在的登陆注册

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

django

上一篇:C#正则表达式

下一篇:oracle 11gr2 RAC virtualbox 安装

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》