Bryan Glazer
Bryan Glazer

Reputation: 852

Saving modelform data from a formview in django

So I'm new to django and I'm struggling with the documentation for class based views. Not really sure what I'm doing wrong here, but this is the problem:

I fill in the appropriate data on the form, click submit and I'm redirected to the same url plus some get parameters that correspond to what I submitted in the form. Nothing new is added to the db. I would like to create a new Advertisement row in the db when I click submit.

I have a ModelForm as follows:

class NewAdForm(ModelForm):
    class Meta:
            model = Advertisement
            exclude = ('campaign',)

    def __init__(self, campaign, *args, **kwargs):
            super(NewAdForm, self).__init__(*args, **kwargs)
            self.campaign = campaign

I also have a FormView:

class AddAdvertView(FormView):
    form_class = NewAdForm
    template_name = 'advertisers/newad.html'

    def get_form_kwargs(self):this
            kwargs = super(AddAdvertView, self).get_form_kwargs()
            kwargs['campaign'] = get_object_or_404(Campaign, id__exact = self.kwargs['campaign_id'])
            return kwargs

    def form_valid(self, form):
            form.save(commit = True)
            return super(AddAdvertView, self).form_valid(form)

And here's the template:

<form action="" method="get">
{{ form.as_p }}
<input type="submit" value="Submit"/>
</form>

Upvotes: 2

Views: 4550

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599590

Any reason why you're using method="get"? The FormView class is probably expecting a POST in order to trigger validation and saving. GET is usually just used to render the initial form.

Upvotes: 3

Chris Pratt
Chris Pratt

Reputation: 239290

It's possible that it's because you're missing the CSRF token, but it really should give you an error about that. Still, try:

<form action="" method="get">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit"/>
</form>

Also, while it doesn't explain why the form isn't saved, you need to specify a success_url on your FormView, the URL the user should be redirected to after successfully submitting the form. I've actually never tried leaving it off, but it's possible that the view is taking you back to the form simply because it doesn't know where else to go.

Upvotes: 0

Related Questions