1.在book app目录下新建一个forms.py,并加入
from django import forms
class RegisterForms(forms.Form):
# test=forms.Field(required=False,label='测试用',initial='请输入用户名',help_text='请输入用户名',
# label_suffix='>>>')
choices={
(1,'male'),(2,'female'),(3,'secret')
}
formats=[
'%Y-%m-%d',
'%m/%d/%Y',
]
year_list=[
1990,1991,1995,2001
]
username=forms.CharField(min_length=4,max_length=10,label='用户名',
widget=forms.TextInput(attrs={'class':'custom-forms'}))
password=forms.CharField(widget=forms.PasswordInput(attrs={'class':'custom-forms'}),min_length=4,max_length=8,label='输入密码')
repassword=forms.CharField(widget=forms.PasswordInput(attrs={'class':'custom-forms'}),min_length=4,max_length=8,label='确认密码')
age=forms.IntegerField(widget=forms.NumberInput(attrs={'class':'custom-forms'}),label='年龄',min_value=18,max_value=120)
gender=forms.MultipleChoiceField(choices=choices,label='性别',widget=forms.CheckboxSelectMultiple,initial=1)
email=forms.EmailField(widget=forms.EmailInput(attrs={'class':'custom-forms'}),label='邮箱')
phone=forms.CharField(widget=forms.TextInput(attrs={'class':'custom-forms'}),max_length=11,label='电话')
birthday=forms.DateField(label='出生日期',widget=forms.SelectDateWidget(years=year_list))
introduce=forms.CharField(widget=forms.Textarea(attrs={'class':'custom-forms'}),label='自我介绍')
urls.py配置路径:
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name="index"),
path('register/',views.IndexForms.as_view(),name='register')
]
views.py中配置视图:
from django.http import HttpResponse
from django.shortcuts import render,redirect,reverse
from django.urls import resolve
from django.views import View
from .forms import RegisterForms
class IndexForms(View):
def get(self,request):
forms =RegisterForms()
return render(request,'index.html',{'forms':forms})
def post(self,request):
forms =RegisterForms(request.POST)
if forms.is_valid():
birthday=forms.cleaned_data.get('birthday')
return render(request,'home.html',{'birthday':birthday})
else:
return HttpResponse('Sorry')
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<link rel="stylesheet" href={% static 'css/index.css' %}>
</head>
<body>
<div class="content">
<form action="" method="post">
<table>
<!--as_p,as_ul-->
{{forms.as_table}}
<tr>
<td><input type="submit" value="submit" name="submit"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
具体页面:
我们只测试接受birthday:注意输入的日期格式。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有