为什么Django的ModelForm验证认为这是无效的?

时间:2010-02-22 23:30:34

标签: python django

我有什么看起来像是一个非常简单的模型设置,模型和使用这两者的视图。唯一的障碍是该模型具有无法POST到表单的用户属性,而应该由request.user填充,所以我有这个:

# models.py
class Update(models.Model):
    user         = models.ForeignKey(User, related_name="updates")
    organisation = models.ForeignKey(Organisation, related_name="updates")
    publish      = models.BooleanField(default=True)



class UpdateForm(ModelForm):
    name = forms.CharField(
        max_length=140,
        required=False,
        widget=forms.TextInput(attrs={"class": "blankable"})
    )

    class Meta(NodeForm.Meta):
        model = Update



# views.py
def status(request):

    from myproject.organisations.models import Organisation
    from myproject.feeds.models         import Update, UpdateForm

    stream = 0
    if request.method == "POST":

        o = request.POST.get("organisation")

        if not o or request.user not in Organisation.objects.get(pk=request.POST.get("organisation")).administrators.all():
            return HttpResponseRedirect(reverse("ethico.core.views.index"))

        f = UpdateForm(request.POST, instance=Update(user=request.user))

        if f.is_valid():
            stream = f.save()
        else:
            stream = f.errors
    ...

每当我运行它时,我总是得到同样的错误:

user: This field is required.

我尝试使用f使用initial属性设置{"user": 1},但仍然说它是必需的。我已经尝试通过将request.POST复制到一个新变量并在将其传递给UpdateForm之前修改它来传递修改后的POST但这很难看。我忘记了什么?

1 个答案:

答案 0 :(得分:1)

您应该尝试排除

形式的用户字段
class UpdateForm(ModelForm):
  name = forms.CharField(
    max_length=140,
    required=False,
    widget=forms.TextInput(attrs={"class": "blankable"})
  )

  class Meta:
    model = Update
    exclude = ("user",)

http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#s-using-a-subset-of-fields-on-the-form