在应用目录下创建form.py文件,利用models.py的模型构建表单
import re
from captcha.fields import CaptchaField
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.core.exceptions import ValidationError
from django.forms import Form, ModelForm # 这个包内也有一个forms,但是不对
from .models import *
# 后端构建表单
# 方式1全部自定义
# class UserRegisterForm(Form):
# username = forms.CharField(max_length=20, min_length=5, error_messages={'min_length': '太短'}, label='用户名:')
# password = forms.CharField(max_length=10, min_length=5, error_messages={'min_length': '太短', 'max_length': '太长'},
# label='密码:', widget=forms.PasswordInput)
# repassword = forms.CharField(max_length=10, min_length=5, error_messages={'min_length': '太短', 'max_length': '太长'},
# label='确认密码:', widget=forms.PasswordInput)
# phone = forms.CharField(required=True, error_messages={'required': '手机号必填'}, label='手机号:', widget=forms.NumberInput)
# email = forms.CharField(required=True, error_messages={'required': '邮箱必填'}, label='邮箱:')
# country = forms.ChoiceField(required=False, widget=forms.RadioSelect,
# choices=(('中国', '中国'), ('美国', '美国'), ('俄国', '俄国')), label='国家')
#
# def clean_email(self):
# """
# 自定义正则验证
# :return:
# """
# email = self.cleaned_data.get('email')
# flag = re.match(r'[a-zA-Z1-9_]\w{4,}@(\w+)\.\w+$', email)
# if not flag:
# raise ValidationError('邮箱有误!')
# return email
# 方式2 对模型内容添加或减少 ModelForm只能用于创建和编辑,不能由于验证
class UserRegisterForm(ModelForm):
class Meta:
model = User
fields = '__all__'
widgets = {'password': forms.PasswordInput}
# 排除字段
exclude = ['is_super', 'user_type']
# 加入字段只能自定义
class UserLoginForm(Form):
username = forms.CharField(max_length=20, min_length=5, error_messages={'min_length': '太短'}, label='用户名:')
password = forms.CharField(max_length=10, min_length=5, error_messages={'min_length': '太短', 'max_length': '太长'},
label='密码:', widget=forms.PasswordInput)
# captcha = CaptchaField(label='验证码')
# 自定义验证
def clean_username(self):
username = self.cleaned_data.get('username')
flag = re.match(r'[a-zA-Z1-9]\w{5,}$', username)
if not flag:
raise ValidationError('用户名格式有误')
return username
在view.py接收请求
def register(request):
if request.method == 'POST':
# 获得表单值
user_register_form = UserRegisterForm(request.POST)
# 验证
flag = user_register_form.is_valid()
if flag:
# 将数据接收形成一个字典
data = user_register_form.cleaned_data
password = make_password(data['password'])
user = User.objects.create(username=data['username'], password=password, phone=data['phone'],
email=data['email'], country=data['country'], usertype_id=1)
if user:
token = str(uuid.uuid4()).replace('-', '')
# 存储到session中
request.session['token'] = token
# 启动异步任务
sendmail.delay(user.id,data['email'],token)
return redirect(reverse('myapp:login'))
return render(request, 'register.html',locals())
else:
user_register_form = UserRegisterForm()
return render(request, "register.html", locals())
def login(request):
if request.method == 'POST':
user_login_form = UserLoginForm(request.POST)
if user_login_form.is_valid():
data = user_login_form.cleaned_data
username = data['username']
password = data['password']
user = User.objects.get(username=username)
if check_password(password, user.password):
request.session['username'] = username
return HttpResponse('登录成功')
else:
print('不成功')
user_login_form = UserLoginForm()
return render(request, 'login.html', locals())
在html页面渲染
{{ user_register_form.as_ul }}
{{ user_login_form.as_p }}
还有很多种as_..
<form action="{% url 'myapp:register' %}" method="post">
{% csrf_token %}
{{ user_register_form.as_ul }}
<input type="submit" value="注册">
{# <p>#}
{# {{ user_register_form.error }}#}
{# </p>#}
</form>
<form action="{% url 'myapp:login' %}" method="post">
{% csrf_token %}
{{ user_login_form.as_p }}
<p><label for="">验证码:</label><input type="text" name="code"><img id="generated_code" src="{% url 'myapp:draw' %}" alt=""></p>
<p><span id="result"></span></p>
<br>
<input type="submit" value="登录">
</form>