django - 如何更改方法 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)
       ...

我为消息制作了一个表单

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

但是当我在 html 中显示表单时,我希望我仅通过“备注”(在 friend 模型中)显示 to_user 的选择列表

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

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”必须是“用户”实例。

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

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

最佳答案

is_valid() 调用表单的 clean() 方法,所以把你的 hack 放在那里:

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

    return self.cleaned_data 

https://stackoverflow.com/questions/8627165/

相关文章:

php - 如何将动态生成的 PDF 文件保存到 zip 文件中?

r - 具有大量数据的热图

asp.net-mvc - ASP.NET MVC 表单例份验证导致登录 url 被调用两次

ruby-on-rails - Rails - I18n - 如何本地化 f.collection_

asp.net - 我该如何解决 : the type or namespace name 'DbM

macos - 从终端的钥匙串(keychain)中删除私钥

xml - HTML 到 XML,反之亦然,并在运行时从 UI - JAXB 使用模式进行验证?

asp.net - 使用分页在 RadGrid Telerik 中查找记录

macos - 为什么 OS X 上缺少 Emacs 图标?

django-admin - Django 管理员覆盖字段集