Daniel Quinn
Daniel Quinn

Reputation: 6389

Why does Django's ModelForm validation think that this is invalid?

I have what looks to me to be a pretty simple setup of model, modelform and a view playing with the two. The only hitch is that the model has a user property that can't be POSTed to the form, rather it should be populated by request.user so I have this:

# 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
    ...

Whenever I run this, I always get the same error:

user: This field is required.

I've tried setting f with the initial attribute using {"user": 1} and it still says that it's required. I've tried passing in a modified POST by copying the request.POST into a new variable and modifying that before passing it to UpdateForm but that's ugly. What am I forgetting here?

Upvotes: 2

Views: 984

Answers (1)

buckley
buckley

Reputation: 2110

You should try excluding the user field in the form

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

Upvotes: 1

Related Questions