Search code examples
djangodjango-class-based-views

Django How to FormView rename context object?


I have a class view which uses FormView. I need to change the name of the form i.e. this is what it used to be in my old function view:

 upload_form = ContactUploadForm(request.user)
 context = {'upload': upload_form,}

With my new view I'm assuming I can rename using the get_context_data method but unsure how.

How can I rename this form to upload instead of form as my templates uses {{ upload }} not {{ form }}? Thanks.

Current Class View:

class ImportFromFile(FormView):

    template_name = 'contacts/import_file.html'
    form_class = ContactUploadForm

    def get_context_data(self, **kwargs):
        """
        Get the context for this view.
        """
        # Call the base implementation first to get a context.
        context = super(ImportFromFile, self).get_context_data(**kwargs)

        return context

Solution

  • Try this:

    class ImportFromFile(FormView):
    
        template_name = 'contacts/import_file.html'
        form_class = ContactUploadForm
    
        def get_context_data(self, **kwargs):
            """
            Get the context for this view.
            """
            kwargs['upload'] = kwargs.pop('form')
            return super(ImportFromFile, self).get_context_data(**kwargs)