如何在方法is_valid()中更改表单字段 [英] how to change form field in method is_valid()

查看:45
本文介绍了如何在方法is_valid()中更改表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型

class Friend(models.Model):
       me = models.ForeignKey(User)
       friend = models.ForeignKey(User)
       remark = models.CharField(max_length=15)

      def __unicode__(self):
            return self.remark

class Message(models.Model):
       from_user = models.ForeignKey(User)
       to_user = models.ForeignKey(User)
       ...

我为Message填写表格

I make a form for Message

class MessageForm(ModelForm):
        class Meta:
              model = Message

但是当我以html格式显示表单时,希望我仅通过'remark'(在Friend模型中)显示to_user的选择列表

but when i display the form in html, i hope i display to_user's choice list just by 'remark' ( in Friend model)

并且我重写MessageForm的 init 方法,如下所示:

and I override MessageForm 's init method like follow:

class MessageForm(ModelForm):
        class Meta:
              model = Message
        def __init__(self,*args,**kwargs):
              super(MessageForm, self).__init__(*args,**kwargs)
              init = kwargs.get('initial')
              if init:
                  if 'from_user' in init:
                       me = init['from_user']
                       self.fields['to_user'].queryset = Friend.objects.filter(me=me)

当数据发布时,form.is_valid()引发错误:无法分配":"Message.to_user"必须是"User"实例.

well when the data post, the form.is_valid() raise error : Cannot assign "": "Message.to_user" must be a "User" instance.

所以我想在调用is_valid()之前更改self.fields ['to_user']的值:

so i want to change self.fields['to_user'] 's value before is_valid() is call like:

def is_valid(self):
     # do something  to fix the problem
     super(MessageForm, self).is_valid()

推荐答案

is_valid()调用表单的 clean()方法,因此将您的hack放在那里:

is_valid() calls the clean() method of the form, so put your hack in there:

def clean(self):
    # hack hack hack, operating on self.cleaned_data

    return self.cleaned_data 

这篇关于如何在方法is_valid()中更改表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆