Form 类定义
定义:在 Django 中,Form 组件用于处理和验证用户输入的数据,Form 类定义在 django.forms
模块中,用于创建表单。通过继承 forms.Form
类,你可以定义表单字段、验证逻辑和表单的其他属性。
1.在fa目录下新增一个froms.py
(定义一个表单类)
from django import formsclass RegisterForm(forms.Form):# max_length 限制输入的字符的最大长度,CharField 文本输入字段类型# username = forms.CharField(max_length=100, label='用户名')username = forms.CharField(widget=forms.TextInput(attrs={'class': 'my-custom-class'}))# EmailField 邮箱输入字段类型email = forms.EmailField(label='邮箱')# widget 用于设置表单控件的样式,PasswordInput 密码输入字段类型password = forms.CharField(widget=forms.PasswordInput, label='密码')# 定义自定义验证逻辑 - 确保用户名不包含特定字符def clean_username(self):username = self.cleaned_data.get('username')if 'admin' in username:raise forms.ValidationError('Username cannot contain "admin"')return username
2.定义方法
# 导入定义的表单类
from .forms import RegisterFormdef register(request):if request.method == 'POST':form = RegisterForm(request.POST)if form.is_valid():username = form.cleaned_data['username']password = form.cleaned_data['password']email = form.cleaned_data['email']return HttpResponse(f"注册成功,用户名:{username}, 密码:{password}, 邮箱:{email}")else:form = RegisterForm()return render(request, 'register.html', {'form': form})
3.在templates目录下新增一个register.html
<!DOCTYPE html>
<html>
<head><title>Register</title>
</head>
<body><h1>Register</h1><form method="post">{% csrf_token %}{{ form.as_p }}<button type="submit">Register</button></form>
</body>
</html>
里面用了{{ form.as_p }}
渲染表单字段,每个字段用 <p>
标签包裹,也可以使用 {{ form.as_table }}
或 {{ form.as_ul }}
来渲染表单
4.增加路由
path('register', views.register, name='register'),
访问链接http://127.0.0.1:8000/article/register
尝试admin注册
当我们正确注册