form的使用

鲁烨
2023-12-01

form的主要作用:

1.在html中生成表单框架,2.验证数据

https://www.cnblogs.com/zongfa/p/7709639.html

1.在model里创建一些数据类型


class Users(models.Model):

   uname = models.CharField(max_length=30,unique=True,verbose_name="用户名")

  upet = models.CharField(max_length=30,verbose_name="昵称")

   upawd = models.CharField(max_length=30,verbose_name="密码")

  email = models.EmailField(verbose_name="电子邮件")

  url = models.URLField(verbose_name="网址")
  1. 在model.py同级目录下新建forms.py

有两种写法:

 (1)定义表单模型

from django import forms

class UserForm(forms.Form):
        uname = forms.CharField(max_length=100 ,label='用户名')
        email = forms.EmailField(label='电子邮件')
        upet = forms.CharField(max_length=30,required=False,label='昵称')  

       upawd = forms.CharField(label='密码',widget=forms.Textarea)
        url = forms.URLField(required=False ,label='网址')



(2)继承model

from django.forms import ModelForm

from myblog.users.models import Users

class UsersForm(ModelForm):

        class Meta:

                model = Users

                fields = ('uname','upet', 'upawd','email','url')




3.在view视图中 ,做表单验证

def contact(request):
    if request.method == 'POST': 
        form = ContactForm(request.POST) 
        if form.is_valid(): 
              username=form.cleaned_data['uname']
              usernick=form.cleaned_data['upet']
              pawd1=form.cleaned_data['upawd']
              email=form.cleaned_data['email']
              weburl=form.cleaned_data['url']
			  Users(uname=username,upet=usernick,upawd=pawd1,
			  email=email,url=weburl).save()
              return HttpResponseRedirect('/index/') 
    	else:
    	

4.在html页面,代码超简单,这点django做的不错

<form action="/contact/" method="post"> 

<table class="form-table">

    <!--{{ form.as_ul }}-->                            # 这是第一种写法,在<ul> 显示表单

   <!-- {{ form.as_p }}-->                            # 这是第二种写法,在<p> 显示表单

     <!--{{ form.as_table }}-->                     # 这是第三种写法,在<table>显示表单

    {% for field in form %}                          # 这是第四种写法,以循环形式显示表单

         {{ field.label_tag }}:{{ field }} 

         {{ field.errors }}

     {% endfor %}

</table> 

<p class="submit"><input type="submit" name="submit" id="submit" class="button-primary" value="注册信息"  /></p> 

</form> 
 类似资料: