Django中form的详解

Django中自带有forms模块,直接使用即可。
例如:

from django import forms

class CommentForm(forms.Form):
      user = forms.CharField(label="用户",max_length=10,required=True,widget=forms.TextInput(attrs={"class":"comment","id":"comment"}))
      content = forms.CharField(label="内容",required=True,widget=forms.Textarea(attrs={"class":"content"}))
      time = forms.DateTimeField(label="提交时间")

第二种

继承ModelForm:根据model生成表单,在实际开发中经常使用。
1、建立model

class Server(models.Model): 
    name = models.CharField(u"名称", max_length=30, null=True, blank=True, unique=True) 
    ip = models.IPAddressField(u"IP地址", max_length=20,unique=True) 
    port = models.IntegerField(u"通信端口") 
    cpunum = models.IntegerField(u"CPU核数", null=True, blank=True) 
    mem = models.IntegerField(u"内存",  null=True, blank=True) 
    state = models.CharField(u"状态", max_length=20, null=True, blank=True) 
    def __unicode__(self): 
        return self.name 
    class Meta: 
        ordering = ['name','ip'] 

2、建立表单

from django.forms import ModelForm 
from .models import Server 
cpunum_choice = ( 
    ('', u"---------"), 
    (2, u"2"),         
    (4, u"4"),         
    (8, u"8"), 
    (16, u"16"), 
) 
class ServerForm(ModelForm): 
    #修改属性    
    cpunum = forms.ChoiceField(label=_(u"CPU核数"),required=True, choices=cpunum_choice) 
    class Meta: 
        model = Server 
    #限定属性
        fields = ('name', 'ip', 'prot', 'cpunum', 'mem') 
    
        

此方法也可以自定义css
如下:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username','password']
        widgets = {
                'username': forms.TextInput(attrs={'class': 'form-control','placeholder':'用户名',}),
                'password': forms.TextInput(attrs={'class': 'form-control','placeholder':'密码',}),
}

修改表单项

level_choice = ( 
    ('ext', u"特急"), 
    ('ugt', u"紧急"),         
    ('nor', u"普通"),    
) 
class ServerForm(ModelForm): 
    level = forms.ChoiceField(label=_(u"任务等级"),required=True, widget=forms.RadioSelect, choices=level_choice) 
    class Meta: 
        model = Server 
        fields = ('name', 'ip', 'prot', 'cpunum', 'mem') 

你可能感兴趣的:(Django中form的详解)