django-表单之创建表单(一)

时间:2022-07-23
本文章向大家介绍django-表单之创建表单(一),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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:注意输入的日期格式。