django中表单使用流程
- 首先创建一个表单类,继承自
django.forms.Form
, 如创建一个注册表单 示例代码如下:
# 表单的简单使用
# 1. 在app 下新建一个文件forms.py, 名字随便,一般叫这个forms.py
from django import forms
class RegisterForms(forms.Form):
username = forms.CharField(label='用户名', max_length=12, min_length=2)
password = forms.CharField(label='密码', max_length=30, min_length=6, widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}), error_messages={'min_length': '密码长度要不小于6位', 'max_length': '密码长度最大为30位'})
password_repeat = forms.CharField(label='请再次输入密码', max_length=30, min_length=6, widget=forms.PasswordInput(attrs={'placeholder': '请再次输入密码'}))
email = form.EmailField(label='邮箱')
# 2. views.py
from django.shortcuts import render, redirect, reverse
from .models import User
from .forms import RegisterForms
def register(request):
if request.method == 'GET':
form = RegisterForms
context = {'form': form}
return render(request, 'forms_test/register.html', context=context)
elif request.method == 'POST':
form = RegisterForms(request.POST):
if form.is_valid():
usernmae = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
password_repeat = form.cleaned_data.get('password_repeat')
email = form.cleaned_data.get('email')
if password == password_repeat:
res = User.objects.get_or_create(name=username, password=password, email=email)
if res[-1]: # 成功注册用户返回 True
return redirect(reverse'login') # 注册成功跳转到登录页面
else:
return redirect(reverse('register')) # 验证不通过重定向到注册页面
return HttpRespose('注册失败, 再次输入的密码不一致')
return HttpResponse('注册失败')
# register.html
<form action='' method="post">
</form>