Bryan Glazer
Bryan Glazer

Reputation: 852

FormView: View didn't return an HttpResponse object

I know this is caused when the view has a code path that doesn't return an HttpResponse, obviously. I'm new to django, so this may be completely wrong.

Here's the FormView code. Do I need to override render_to_response?

class AddAdvertView(FormView):
    form_class = NewAdForm

    def get(self, *args, **kwargs):
            self.campaign = get_object_or_404(Campaign, id__exact = self.kwargs['campaign_id'])

    def post(self, request, *args, **kwargs):
            pass

    def get_form(self, form_class):
            return form_class(initial = {}, campaign = self.campaign)

    def get_success_url(self):
            return self.request.META.get('HTTP_REFERER', None)

    def form_valid(self, form):
            return HttpResponse('form valid')

    def form_invalid(self, form):
            return HttpResponse('form invalid')

Upvotes: 1

Views: 2494

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174632

This is probably what you want in your get method:

 def get(self, *args, **kwargs):
     campaign = get_object_or_404(Campaign, id=self.kwargs['campaign_id'])
     ctx = self.get_context_data()
     ctx['campaign'] = campaign
     return self.render_to_response(ctx)

If you aren't doing anything with post, you shouldn't have a method to override it. Similarly you don't need to override get_form.

Class based views are new in django and their documentation isn't up to par with the other components; hopefully this will change soon. For now, the best place to find out how class based views work is look at what their mixins provide.

For FormView, the mixins are FormMixin and ProcessFormView

Upvotes: 5

ilvar
ilvar

Reputation: 5841

You should return something from post and get methods, at least super(AddAdvertView, self).get(*args, **kwargs). In your code get just created an attribute (though it should return an empty form), and post does nothing at all (though it should process the form). It seems you should not redefine post and get at all, and retrieve your campaign in the dispatch method (don't forget to call super(AddAdvertView, self).dispatch(dispatch arguments))

Upvotes: 2

Related Questions