一、内置 User 实现注册登录
Django 已内置了用户管理功能,即 Auth 认证系统, 而且具有灵活的扩展性,可以满足多方面的开发需求。
1、编写 views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.shortcuts import reverse
def shopperView(request):
return render(request, 'shopper.html')
def loginView(request):
title = '用户登录'
classContent = 'logins'
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
if User.objects.filter(username=username):
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect(reverse('shopper:shopper'))
else:
state = '注册成功'
d = dict(username=username, password=password, is_staff=1, is_active=1)
user = User.objects.create_user(**d)
user.save()
return render(request, 'login.html', locals())
def logoutView(request):
return render(request)
def shopcartView(request):
return render(request, 'shopcart.html')
2、编写 login.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="login-bg">
<div class="login-cont w1200">
<div class="form-box">
<form class="layui-form" action="" method="post">
{% csrf_token %}
<legend>手机号注册登录</legend>
<div class="layui-form-item">
<div class="layui-inline iphone">
<div class="layui-input-inline">
<i class="layui-icon layui-icon-cellphone iphone-icon"></i>
<input name="username" id="username" lay-verify="required|phone" placeholder="请输入手机号" class="layui-input">
</div>
</div>
<div class="layui-inline iphone">
<div class="layui-input-inline">
<i class="layui-icon layui-icon-password iphone-icon"></i>
<input id="password" type="password" name="password" lay-verify="required|password" placeholder="请输入密码" class="layui-input">
</div>
</div>
</div>
<p>{{ state }}</p>
<div class="layui-form-item login-btn">
<div class="layui-input-block">
<button class="layui-btn" lay-submit="" lay-filter="demo1">注册/登录</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock content %}
{% block footer %}
<div class="footer">
<div class="ng-promise-box">
<div class="ng-promise w1200">
<p class="text">
<a class="icon1" href="javascript:;">7天无理由退换货</a>
<a class="icon2" href="javascript:;">满99元全场免邮</a>
<a class="icon3" style="margin-right: 0" href="javascript:;">100%品质保证</a>
</p>
</div>
</div>
<div class="mod_help w1200">
<p>
<a href="javascript:;">关于我们</a>
<span>|</span>
<a href="javascript:;">帮助中心</a>
<span>|</span>
<a href="javascript:;">售后服务</a>
<span>|</span>
<a href="javascript:;">母婴资讯</a>
<span>|</span>
<a href="javascript:;">关于货源</a>
</p>
<p class="coty">母婴商城版权所有 © 2012-2020</p>
</div>
</div>
{% endblock footer %}
{% block script %}
layui.config({
base: '{% static 'js/' %}'
}).use(['jquery','form'],function(){
var $ = layui.$,form = layui.form;
$("#find").click(function() {
if(!/^1\d{10}$/.test($("#username").val())){
layer.msg("请输入正确的手机号");
return false;
}
})
})
{% endblock script %}
二、使用 Form 实现注册登录
1、定义form.py
在 shopper 文件夹里面新建 form.py ,然后编写:
from django import forms
from django.core.exceptions import ValidationError
class LoginForm(forms.Form):
username = forms.CharField(max_length=11, label='请您输入手机号',
widget=forms.widgets.TextInput(
attrs={'class': 'layui-input', 'placeholder': '请您输入手机号',
'lay-verify': 'required|phone', 'id': 'username'}), )
password = forms.CharField(max_length=20, label='请您输入密码',
widget=forms.widgets.PasswordInput(
attrs={'class': 'layui-input', 'placeholder': '请您输入密码',
'lay-verify': 'required|password', 'id': 'password'}), )
# 自定义表单字段username的数据清洗
def clean_username(self):
if len(self.cleaned_data['username']) == 11:
return self.cleaned_data['username']
else:
raise ValidationError('用户名为手机号码')
2、编写 view.py
from django.shortcuts import render, redirect
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.models import User
from django.shortcuts import reverse
from .form import *
def shopperView(request):
return render(request, 'shopper.html')
def loginView(request):
title = '用户登录'
classContent = 'logins'
if request.method == 'POST':
infos = LoginForm(data=request.POST)
if infos.is_valid():
data = infos.cleaned_data
username = data['username']
password = data['password']
if User.objects.filter(username=username):
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect(reverse('shopper:shopper'))
else:
state = '注册成功'
d = dict(username=username, password=password, is_staff=1, is_active=1)
user = User.objects.create_user(**d)
user.save()
else:
# 获取错误信息,并以JSON格式输出
error_msg = infos.errors.as_json()
print(error_msg)
else:
infos = LoginForm()
return render(request, 'login.html', locals())
def logoutView(request):
return render(request)
def shopcartView(request):
return render(request, 'shopcart.html')
3、编写 login.html
用户注册登录表单的元素控件交由表单类 LoginForm 实现,因此模板文件 login.html 无须使用 HTML 语言编写网页表单的元素控件,将元素控件改由模板变量 infos 生成:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="login-bg">
<div class="login-cont w1200">
<div class="form-box">
<form class="layui-form" action="" method="post">
{% csrf_token %}
<legend>手机号注册登录</legend>
<div class="layui-form-item">
<div class="layui-inline iphone">
<div class="layui-input-inline">
<i class="layui-icon layui-icon-cellphone iphone-icon"></i>
{{ infos.username }}
</div>
</div>
<div class="layui-inline iphone">
<div class="layui-input-inline">
<i class="layui-icon layui-icon-password iphone-icon"></i>
{{ infos.password }}
</div>
</div>
</div>
<p>{{ state }}</p>
<div class="layui-form-item login-btn">
<div class="layui-input-block">
<button class="layui-btn" lay-submit="" lay-filter="demo1">注册/登录</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock content %}
{% block footer %}
<div class="footer">
<div class="ng-promise-box">
<div class="ng-promise w1200">
<p class="text">
<a class="icon1" href="javascript:;">7天无理由退换货</a>
<a class="icon2" href="javascript:;">满99元全场免邮</a>
<a class="icon3" style="margin-right: 0" href="javascript:;">100%品质保证</a>
</p>
</div>
</div>
<div class="mod_help w1200">
<p>
<a href="javascript:;">关于我们</a>
<span>|</span>
<a href="javascript:;">帮助中心</a>
<span>|</span>
<a href="javascript:;">售后服务</a>
<span>|</span>
<a href="javascript:;">母婴资讯</a>
<span>|</span>
<a href="javascript:;">关于货源</a>
</p>
<p class="coty">母婴商城版权所有 © 2012-2020</p>
</div>
</div>
{% endblock footer %}
{% block script %}
layui.config({
base: '{% static 'js/' %}'
}).use(['jquery','form'],function(){
var $ = layui.$,form = layui.form;
$("#find").click(function() {
if(!/^1\d{10}$/.test($("#username").val())){
layer.msg("请输入正确的手机号");
return false;
}
})
})
{% endblock script %}
三、使用 ModelForm 实现注册登录
1、编写 form.py
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
class LoginModelForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'password')
labels = {
'username': '请您输入手机号',
'password': '请您输入密码',
}
error_messages = {
'__all__': {'required': '请输入内容',
'invalid': '请检查输入内容'},
}
# 定义widgets,设置表单字段对应HTML元素控件的属性
widgets = {
'username': forms.widgets.TextInput(
attrs={'class': 'layui-input', 'placeholder': '请您输入手机号',
'lay-verify': 'required|phone', 'id': 'username'}),
'password': forms.widgets.PasswordInput(
attrs={'class': 'layui-input', 'placeholder': '请您输入密码',
'lay-verify': 'required|password', 'id': 'password'})
}
# 自定义表单字段username的数据清洗
def clean_username(self):
if len(self.cleaned_data['username']) == 11:
return self.cleaned_data['username']
else:
raise ValidationError('用户名为手机号码')
2、编写 views.py
from django.shortcuts import render, redirect
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.models import User
from django.shortcuts import reverse
from .form import *
def shopperView(request):
return render(request, 'shopper.html')
def loginView(request):
title = '用户登录'
classContent = 'logins'
if request.method == 'POST':
infos = LoginModelForm(data=request.POST)
data = infos.data
username = data['username']
password = data['password']
if User.objects.filter(username=username):
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect(reverse('shopper:shopper'))
else:
state = '注册成功'
d = dict(username=username, password=password, is_staff=1, is_active=1)
user = User.objects.create_user(**d)
user.save()
else:
infos = LoginModelForm()
return render(request, 'login.html', locals())
def logoutView(request):
return render(request)
def shopcartView(request):
return render(request, 'shopcart.html')
四、个人中心页
1、在应用 shopper 的 views.py 定义视图函数 shopperView
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.models import User
from django.shortcuts import reverse
from .form import *
from .models import OrderInfos
@login_required(login_url='/shopper/login.html')
def shopperView(request):
title = '个人中心'
classContent = 'informations'
p = request.GET.get('p', 1)
# 处理已支付的订单
t = request.GET.get('t', '')
payTime = request.session.get('payTime', '')
if t and payTime and t == payTime:
payInfo = request.session.get('payInfo', '')
OrderInfos.objects.create(**payInfo)
del request.session['payTime']
del request.session['payInfo']
# 根据当前用户查询用户订单信息
orderInfos = OrderInfos.objects.filter(user_id=request.user.id).order_by('-created')
# 分页功能
paginator = Paginator(orderInfos, 7)
try:
pages = paginator.page(p)
except PageNotAnInteger:
pages = paginator.page(1)
except EmptyPage:
pages = paginator.page(paginator.num_pages)
return render(request, 'shopper.html', locals())
def loginView(request):
title = '用户登录'
classContent = 'logins'
if request.method == 'POST':
infos = LoginModelForm(data=request.POST)
data = infos.data
username = data['username']
password = data['password']
if User.objects.filter(username=username):
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect(reverse('shopper:shopper'))
else:
state = '注册成功'
d = dict(username=username, password=password, is_staff=1, is_active=1)
user = User.objects.create_user(**d)
user.save()
else:
infos = LoginModelForm()
return render(request, 'login.html', locals())
def logoutView(request):
return render(request)
def shopcartView(request):
return render(request, 'shopcart.html')
2、编写 shopper.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="info-list-box">
<div class="info-list">
<div class="item-box layui-clear" id="list-cont">
<div class="item">
<div class="img">
<img src="{% static 'img/portrait.png' %}">
</div>
<div class="text">
<h4>用户:{{ user.username }}</h4>
<p class="data">登录时间:{{ user.last_login }}</p>
<div class="left-nav">
<div class="title">
<a href="{% url 'shopper:shopcart' %}">我的购物车</a>
</div>
{# <div class="title">#}
{# <a>我的优惠卷</a>#}
{# </div>#}
{# <div class="title">#}
{# <a>收货地址</a>#}
{# </div>#}
<div class="title">
<a href="{% url 'shopper:logout' %}">退出登录</a>
</div>
</div>
</div>
</div>
<div class="item1">
<div class="cart">
<div class="cart-table-th">
<div class="th th-item">
<div class="th-inner">
订单编号
</div>
</div>
<div class="th th-price">
<div class="th-inner">
订单价格
</div>
</div>
<div class="th th-amount">
<div class="th-inner">
购买时间
</div>
</div>
<div class="th th-sum">
<div class="th-inner">
订单状态
</div>
</div>
</div>
<div class="OrderList">
<div class="order-content" id="list-cont">
{% for p in pages.object_list %}
<ul class="item-content layui-clear">
<li class="th th-item">{{ p.id }}</li>
<li class="th th-price">¥{{ p.price|floatformat:'2' }}</li>
<li class="th th-amount">{{ p.created }}</li>
<li class="th th-sum">{{ p.state }}</li>
</ul>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
<div id="demo0" style="text-align: center;">
<div class="layui-box layui-laypage layui-laypage-default" id="layui-laypage-1">
{% if pages.has_previous %}
<a href="{% url 'shopper:shopper' %}?p={{ pages.previous_page_number }}" class="layui-laypage-prev">上一页</a>
{% endif %}
{% for page in pages.paginator.page_range %}
{% if pages.number == page %}
<span class="layui-laypage-curr"><em class="layui-laypage-em"></em><em>{{ page }}</em></span>
{% elif pages.number|add:'-1' == page or pages.number|add:'1' == page %}
<a href="{% url 'shopper:shopper' %}?p={{ page }}">{{ page }}</a>
{% endif %}
{% endfor %}
{% if pages.has_next %}
<a href="{% url 'shopper:shopper' %}?p={{ pages.pages.next_page_number }}" class="layui-laypage-next">下一页</a>
{% endif %}
</div>
</div>
</div>
{% endblock content %}
{% block script %}
layui.config({
base: '{% static 'js/' %}'
}).use(['mm','laypage'],function(){
var mm = layui.mm,laypage = layui.laypage;
});
{% endblock script %}
五、运行
运行项目点击个人中心进行注册登录操作并且看到个人信息页面,就代表目前为止一切顺利啦。
|