Bootstrap

使用django框架实现登陆页面(将登陆用户的记录保存在浏览器cookie中)

1、创建url

 path('login/',account.login),

2、登陆html页面

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
    <style>
        .account {
            width: 400px;
            border: 1px solid #dddddd;
            border-radius: 5px;
            box-shadow: 5px 5px 20px #aaa;

            margin-left: auto;
            margin-right: auto;
            margin-top: 100px;
            padding: 20px 40px;
        }

        .account h2 {
            margin-top: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
<div class="account">
    <h2>用户登陆</h2>
    <form method="post" novalidate>
        {#        novalidate去掉自身所带的错误提示没填东西直接提交#}
        {#        使用post请求需要加上#}
        {% csrf_token %}
        <div class="form-group">
            <label>用户名</label>
            {{ form.username }}
            <span style="color: red">{{ form.username.errors.0 }}</span>
        </div>
        <div class="form-group">
            <label>密码</label>
            {{ form.password }}
            <span style="color: red">{{ form.password.errors.0 }}</span>
        </div>
        <input type="submit" value="登 陆" class="btn btn-primary">
    </form>
</div>

</body>
</html>

3、视图函数的书写

from django.shortcuts import render,redirect
from app01.utils.bootstrap import BootStrapForm
from django import forms
from app01.utils.encrypt import md5
from app01 import models

class LoginForm(BootStrapForm):
    username=forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        # 设置为必填属性
        required=True

    )
    password=forms.CharField(
        label="密码",
        widget=forms.PasswordInput(render_value=True),
        required=True
    )

    def clean_password(self):
        pwd=self.cleaned_data.get("password")
        return md5(pwd)
def login(request):
    if request.method=="GET":
        form=LoginForm()
        return render(request,'login.html',{"form":form})

    form=LoginForm(data=request.POST)
    if form.is_valid():
        admain_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admain_object:
            # 在password字段下显示
            form.add_error("password","用户名或密码错误")
            return render(request,'login.html',{'form':form})
        # 用户名和密码都正确
        # 网站生成随机字符串;写到用户浏览器的cookie;在写入到session中
        request.session["info"]={'id':admain_object.id,'name':admain_object.username}
        return redirect("/admain/list/")

    return render(request, 'login.html', {'form': form})

;