User Register and Login
用户的注册页面和登录页面
A-基本页面
-在usls。py中创建register和login的url
-在viesw中写入registerPage函数
-引入数据库USER中的Form-UserCreationForm
from django.contrib.auth.forms import UserCreationForm def registerPage(request): form = UserCreationForm() if request.method=='POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request,'accounts/register.html',context)
-在template模板中写入register。html
-{{form_as.p}} 使其按顺序排列
-在forms.py中自定义model 引入User 选择属性
from django.forms import ModelForm from .models import Order from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' class CreatUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2']
-更改有关views中的引入函数
from .forms import OrderForm,CreatUserForm form = CreatUserForm() form = CreatUserForm(request.POST)
-在r127.0.0.1/register 添加数据 从127.0.0.1/admin/User中查找
B 渲染模板
-在register。html中修改页面的渲染方式 单个单个渲染方便后面套用JS
<h3>Register</h3> <form method="POST" action=""> {% csrf_token %} {{ form.username.label }} {{ form.username }} {{ form.email.label }} {{ form.email }} {{ for.password1.label }} {{ form.password1 }} {{ form.password2.label }} {{ form.password2 }} <input type="submit" name="Create User"> </form>
-访问 jsfiddle 找到js 渲染模板
-注册表格模板: https://jsfiddle.net/ivanov11/hzf0jxLg/
<!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } .login_btn:focus { box-shadow: none !important; outline: 0px !important; } .login_container { padding: 0 2rem; } .input-group-text { background: #f7ba5b !important; color: white !important; border: 0 !important; border-radius: 0.25rem 0 0 0.25rem !important; } .input_user, .input_pass:focus { box-shadow: none !important; outline: 0px !important; } </style> </head> <body> <div class="container h-100"> <div class="d-flex justify-content-center h-100"> <div class="user_card"> <div class="d-flex justify-content-center"> <h3 id="form-title">REGISTER ACCOUNT</h3> </div> <div class="d-flex justify-content-center form_container"> <form method="POST" action=""> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> {{form.username}} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-envelope-square"></i></span> </div> {{form.email}} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> {{form.password1}} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> {{form.password2}} </div> <div class="d-flex justify-content-center mt-3 login_container"> <input class="btn login_btn" type="submit" value="Register Account"> </div> </form> </div> {{form.errors}} <div class="mt-4"> <div class="d-flex justify-content-center links"> Already have an account? <a href="{% url 'login' %}" class="ml-2">Login</a> </div> </div> </div> </div> </div> <script> /* Because i didnt set placeholder values in forms.py they will be set here using vanilla Javascript //We start indexing at one because CSRF_token is considered and input field */ //Query All input fields var form_fields = document.getElementsByTagName('input') form_fields[1].placeholder='Username..'; form_fields[2].placeholder='Email..'; form_fields[3].placeholder='Enter password...'; form_fields[4].placeholder='Re-enter Password...'; for (var field in form_fields){ form_fields[field].className += ' form-control' } </script> </body> </html> {#<h3>Register</h3>#} {#<form method="POST" action="">#} {# {% csrf_token %}#} {# {{ form.username.label }}#} {# {{ form.username }}#} {##} {# {{ form.email.label }}#} {# {{ form.email }}#} {##} {# {{ for.password1.label }}#} {# {{ form.password1 }}#} {##} {# {{ form.password2.label }}#} {# {{ form.password2 }}#} {# <input type="submit" name="Create User">#} {#</form>#}
-登录表单模板: https://jsfiddle.net/ivanov11/dghm5cu7/
<!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } .login_btn:focus { box-shadow: none !important; outline: 0px !important; } .login_container { padding: 0 2rem; } .input-group-text { background: #f7ba5b !important; color: white !important; border: 0 !important; border-radius: 0.25rem 0 0 0.25rem !important; } .input_user, .input_pass:focus { box-shadow: none !important; outline: 0px !important; } #messages{ background-color: grey; color: #fff; padding: 10px; margin-top: 10px; } </style> </head> <body> <div class="container h-100"> <div class="d-flex justify-content-center h-100"> <div class="user_card"> <div class="d-flex justify-content-center"> <h3 id="form-title">LOGIN</h3> </div> <div class="d-flex justify-content-center form_container"> <form method="POST" action=""> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> <input type="text" name="username" placeholder="Username..." class="form-control"> </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> <input type="password" name="password" placeholder="Password..." class="form-control" > </div> <div class="d-flex justify-content-center mt-3 login_container"> <input class="btn login_btn" type="submit" value="Login"> </div> </form> </div> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} <div class="mt-4"> <div class="d-flex justify-content-center links"> Don't have an account? <a href="{% url 'register' %}" class="ml-2">Sign Up</a> </div> </div> </div> </div> </div> </body> </html>
C 关于登录错误信息提示Flash
-查看django文档引入库 from django.contrib import messages
-在registerPage函数下if通过时添加
from django.contrib import messages def registerPage(request): form = CreatUserForm() if request.method=='POST': form = CreatUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request,'Accounts was created for '+ user) return redirect('login') context = {'form': form} return render(request,'accounts/register.html',context)
-在login。html中添加{{message}}
{% for message in messages %} <p id="messages">{{message}}</p> {% endfor %}
D用户输入账号密码登录后的操作
引入验证,登录,注销 库
form django.contrib.auth import authenticate , login , logout
-用户注册好账号密码 然后跳转到login页面登录
-在loginPage函数下添加代码
-authenticate 目的是验证账号密码 login目的的进行登录 ( def loginPage() 的起名才不会和这个相撞)
def loginPage(request): if request.method =='POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username,password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request,'Account or Password is incorrect') return render(request, 'accounts/login.html')
-关于注销
- 在urls。py中增加 logout 的url
-在views中增加函数 logouUser
def logoutUser(request): logout(request) return redirect('login')
-要对Navtar.html中添加操作
<style> .hello-msg{ font-size: 18px; color: #fff; margin-right: 20px; } </style> <span class="hello-msg">Hello, {{request.user}}</span> <span ><a class="hello-msg" href="{% url 'logout' %}">Logout</a></span>
E 限制需要登录用户才能进入后台管理
-引入 login装饰器库
from django.contrib.auth.decorators import login_required
-在每一个后台管理函数前面添加代码
@loin_required(login_url = 'login')
@login_required(login_url='login') def home(request): customer = Customer.objects.all() order = Order.objects.all() total_order = order.count() Delivered = Order.objects.filter(status='Delivered').count() Pending = Order.objects.filter(status='Pending').count() context = {'customer':customer,'order':order,'total_order':total_order,'Delivered':Delivered,'Pending':Pending} return render(request, 'accounts/home.html',context)
F代码优化 (重定向)
-对于已经登录了的用户 不需要也不想要再看见注册或登录页面 如果他们点击登录页面或注册页面 可以直接重定向带后台管理系统
-引入库
from django.contrib.auth import authenticate
def registerPage(request): if request.user.is_authenticated: return redirect('home') else: form = CreatUserForm() if request.method=='POST': form = CreatUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request,'Accounts was created for '+ user) return redirect('login') context = {'form': form} return render(request,'accounts/register.html',context) def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method =='POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username,password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request,'Account or Password is incorrect') return render(request, 'accounts/login.html')