Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 570
GrantU Avatar asked Dec 20 '22 04:12

GrantU


1 Answers

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)
like image 137
Andrei Kaigorodov Avatar answered Dec 28 '22 07:12

Andrei Kaigorodov