zoukankan      html  css  js  c++  java
  • Django基于cookies实现完整登录

    创建项目与应用

    django-admin startproject mysite
    python manage startapp online
    
    

      创建完成后目录构如下:

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

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'online',
    ]
    

    设计数据库

       打开mysite/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 __str__(self):
            return self.username
    

      创建数据库和User表,最后生成的online_user表就是我们models.py中创建的User类。

    配制URL

       打开mysite/mysite/urls.py:

    from django.conf.urls import url,include
    from django.contrib import admin
    from online import urls
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^online/',include('online.urls')),
    ]
    

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

    from django.conf.urls import url,include
    from online import views
    
    urlpatterns = [
        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'),
    ]
    

    http://127.0.0.1:8000/online 登录页
    http://127.0.0.1:8000/online/login/ 登录页
    http://127.0.0.1:8000/online/regist/ 注册页
    http://127.0.0.1:8000/online/index/ 登录成功
    http://127.0.0.1:8000/online/logout/ 注销

    创建视图

       打开mysite/onlie/views.py文件:

    from django.shortcuts import render,HttpResponse
    from django import forms
    from .models import User
    
    # Create your views here.
    #表单
    class UserForm(forms.Form):
        username = forms.CharField(label='用户名:',max_length=50)
        password = forms.CharField(label='密码:',max_length=50)
    
    
    #注册
    def regist(request):
        if request.method == 'POST':
            uf = UserForm(request.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 sucess!!')
        else:
            uf = UserForm()
        return render(request,'regist.html',{'uf':uf})
    
    #登录
    def login(request):
        if request.method == 'POST':
            uf = UserForm(request.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:
                    respone = render(request,'index.html')
                    # 将username写入浏览器cookie,失效时间为3600
                    respone.set_cookie('username',username,3600)
                    return  respone
                else:
                    return render(request,'login.html',{'uf':uf})
        else:
            uf = UserForm()
        return render(request,'login.html',{'uf':uf})
    
    #登录成功
    def index(request):
        username = request.COOKIES.get('username',None)
        return render(request,'index.html',{'username':username})
    
    
    #退出
    def logout(request):
        response = HttpResponse('logout!!!')
        #清理cookie
        response.delete_cookie('username')
        return response
    

    创建模板

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

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>注册</title>
    </head>
    
    <body>
    <h1>注册页面:</h1>
    <form method = 'post' enctype="multipart/form-data">
        {% csrf_token %}
        {{uf.as_p}}
        <input type="submit" value = "ok" />
    </form>
    <br>
    <a href="http://127.0.0.1:8000/online/login/">登陆</a>
    </body>
    </html>
    

      在mysite/onlie/templates/目录下创建login.html文件:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>登陆</title>
    </head>
    
    <body>
    <h1>登陆页面:</h1>
    <form method = 'post' enctype="multipart/form-data">
        {% csrf_token %}
        {{uf.as_p}}
        <input type="submit" value = "ok" />
    </form>
    <br>
    <a href="http://127.0.0.1:8000/online/regist/">注册</a>
    </body>
    </html>
    

      在mysite/onlie/templates/目录下创建index.html文件:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title></title>
    </head>
    
    <body>
    <h1>welcome {{username}} !</h1>
    <br>
    <a href="http://127.0.0.1:8000/online/logout/">退出</a>
    </body>
    </html>
    

    使用功能

      注册:

      登录:

      查看cookies:

      点击退出后,cookies中将不再显示用户名信息。

  • 相关阅读:
    使非标准 Win32 控件或自画控件也具有 Windows XP 的界面风格
    MapInfo格式到ArcInfo格式的转换
    DICOM医学图像文件格式
    香港身份证
    Cheap Tricks: Let's Talk About METADATA TypeLibs
    ASP中使用ADO访问数据源
    DirectX 9 编程 DirectX窗口
    3DES Source Code
    OLEDB Resource(Session) Pooling (在Ado开发中使用连接池)
    《仙剑奇侠传4》仙剑问答全答案
  • 原文地址:https://www.cnblogs.com/postgres/p/5923786.html
Copyright © 2011-2022 走看看