Why {{ form }} represents a form instance in template file?

Viewed 91

According to django official doc,

All you need to do to get your form into a template is to place the form instance into the template context. So if your form is called form in the context, {{ form }} will render its <label> and <input> elements appropriately.

Where is the form instance named/defined as form for template context in django source code? and How can I change the name to something else {{ my_form }} for example ?

2 Answers

When rendering your view in Views.py you can do the following to change the name of the form that you render:

Views.py

from .forms import MyForm1

def MyForm(request):
    my_form = Myform1
    return render(request , 'MyForm.html' , {'my_form' : my_form})

Then when calling your form on the HTML page you can call it as

{{ my_form }}

As you aptly say in your comment:

Context means the repository of data used for rendering via HTML template files.

As to how form is passed to the context if you use a function based view, this is completely upto you with what key you pass the form, for example below code will pass it as my_form:

return render(request, 'template.html', {'my_form': my_form})

In case of a class based view most of them inherit from ContextMixin which declares the method get_context_data that is used to pass variables into the context. All class based views that deal with forms also inherit from FormMixin, looking at its source code it overrides get_context_data to pass the form into the context:

def get_context_data(self, **kwargs):
    """Insert the form into the context dict."""
    if 'form' not in kwargs:
        kwargs['form'] = self.get_form()
    return super().get_context_data(**kwargs)

Of course you can decide to again override get_context_data yourself and pass the form with some other name, but doing so wouldn't be very useful:

class YourView(CreateView):
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['my_form'] = context['form']
        return context
Related