9
from forms import MyContactForm
from django.views.generic.edit import FormView 

class MyFormView(FormView):
    template_name = 'my_forms.html'                                      
    form_class = MyContactForm  
    success_url = '/thanks/' 

In my template, the form is called like this:

{{ form }}

But how can I call it like this:

{{ my_contact_form }}?

This would be the forms equivalent of object_context_name(for models).

Bentley4
  • 10,678
  • 25
  • 83
  • 134

1 Answers1

9

You could override get_context_data:

class MyFormView(FormView):
    template_name = 'my_forms.html'                                      
    form_class = MyContactForm  
    success_url = '/thanks/' 

    # from ContextMixin via FormMixin    
    def get_context_data(self, **kwargs):
        data = super(MyFormView, self).get_context_data(**kwargs)

        data['my_contact_form'] = data.get('form')

        return data
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
  • Do you have any idea what to do when you want to use multiple forms? I just thought passing each of them them to a data key and just dropping `form_class`. But I get a `TypeError, NoneType is not callable` when I do that. – Bentley4 Mar 25 '13 at 13:00
  • 1
    You can only submit one form. `generic.edit.FormView` manages one form. Look at the [source of FormMixin and ProcessFormView](https://github.com/django/django/blob/master/django/views/generic/edit.py): you'll have to override `get` and `form_invalid` to render all the forms and you'll have to override `post` to determine what form was submitted and process it. At this point, I don't think you should inherit from `FormView`. – Pavel Anossov Mar 25 '13 at 13:28
  • 1
    Check http://stackoverflow.com/questions/6276398/multiple-form-classes-in-django-generic-class-views, especially the second update to the accepted answer. – Berislav Lopac Mar 26 '13 at 13:35