溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django1.7中注冊、登陸、以及cookie的使用

發(fā)布時(shí)間:2020-04-01 05:35:42 來源:網(wǎng)絡(luò) 閱讀:770 作者:飛俠119 欄目:開發(fā)技術(shù)

創(chuàng)建項(xiàng)目與應(yīng)用

#django-admin.pystartproject myadmin

#cd myadmin

#python manage.py startapp online

Django1.7中注冊、登陸、以及cookie的使用

打開myadmin/myadmin/settings.py文件,將應(yīng)用添加進(jìn)去:

Django1.7中注冊、登陸、以及cookie的使用

設(shè)計(jì)數(shù)據(jù)庫  

打開myadmin/online/models.py文件,添加如下內(nèi)容:

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

下面進(jìn)行數(shù)據(jù)庫的同步:

# 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/目錄下創(chuàng)建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'),
)

創(chuàng)建視圖  

打開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():
            #獲得表單數(shù)據(jù)
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            #添加到數(shù)據(jù)庫
            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']
            #獲取的表單數(shù)據(jù)與數(shù)據(jù)庫進(jìn)行比較
            user = User.objects.filter(username__exact = username,password__exact = password)
            if user:
                #比較成功,跳轉(zhuǎn)index
                response = HttpResponseRedirect('/online/index/')
                #將username寫入瀏覽器cookie,失效時(shí)間為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

這里實(shí)現(xiàn)了所有注冊,登陸邏輯,中間用到cookie創(chuàng)建,讀取,刪除操作等。

創(chuàng)建模板

先在mysite5/online/目錄下創(chuàng)建templates目錄,接著在mysite5/online/templates/目錄下創(chuàng)建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>

<a>登陸</a>

</body>

</html>

myadmin/online/templates/目錄下創(chuàng)建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>

<a>注冊</a>

</body>

</html>

myadmin/online/templates/目錄下創(chuàng)建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>

<a>退出</a>

</body>

</html>

使用功能

注冊


Django1.7中注冊、登陸、以及cookie的使用

登陸

Django1.7中注冊、登陸、以及cookie的使用



向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI