LOADING

Follow me

Django 表单处理(二)
十二月 5, 2013|IT

Django 表单处理(二)


ModelForm

class MyComment(models.Model):


    #===显示的中文名称,可以直接在这里定义,也可以在 views.py 中相应方法处理.
    yourname = models.CharField(‘名称’,max_length=50)
    website = models.URLField()
    email = models.EmailField()
    content = models.TextField(‘内容’)
    qq = models.CharField(max_length=20)
    msn = models.CharField(max_length=100)

    hiddenfields1 = models.CharField(max_length=50)

class TestModelForm(ModelForm):

    class Meta:

        model = MyComment

        #==只显示这几个字段================

        fields = (‘yourname’,’email’,’website’,’content’,’qq’,’msn’)

        #==或者用排除法

        #exclude = (‘hiddenfields1’,)

    

    #===如果需要变更样式, 或者变更显示中文名称.更改 label    

    def __init__(self, *args, **kwargs):

        super(TestModelForm, self).__init__(*args, **kwargs)

        #====改变样式,也可以赋值 class=???,在外面html页面上先定义好,个人不推荐直接在代码里写,只是为了演示。

        self.fields[‘yourname’].widget.attrs.update({‘style’ : ‘border:1px dashed #ccc;’})

        self.fields[’email’].label=’伊妹儿’

        

        

def add_model_comment(request):

    context={}

    context.update(csrf(request))

    form = TestModelForm()

    context[‘form’]=form

    return render_to_response(‘modelform.html’,context)


def save_model_comment(request):

    form = TestModelForm(request.POST)

    if form.is_valid() :

        print ‘successs’

        yourname = form.cleaned_data[‘yourname’]

        website = form.cleaned_data[‘website’]

        email = form.cleaned_data[’email’]

        content = form.cleaned_data[‘content’]

        qq = form.cleaned_data[‘qq’]

        msn = form.cleaned_data[‘msn’]

        #===想干嘛就干嘛,可以插入数据库等

        print ‘get information:’,yourname,email,website,content,qq,msn

        return render_to_response(‘modelform.html’,locals())

    else:

        print ‘error’

        return render_to_response(‘modelform.html’,locals())




版权声明:本文为博主原创文章,未经博主允许不得转载。

no comments
Share

发表评论