1

I know this question was asked before, but the accepted answer does not really answer the question: where `form.as_p`in django templates come from?

In Django doc:

Example myapp/views.py:

from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

Example myapp/author_form.html:

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save">
</form>

The question is, where does the template get the 'form' context from, since we did not explicitly define a render() function inside the AuthorCreate class? Thanks.

A.G.
  • 37
  • 8

1 Answers1

0

I found the answer.

CreateView inherits the get method from ProcessFormView class and the get_context_data method from the FormMixin class.

As you can see in the code, the get method returns an expression that calls get_context_data.

class ProcessFormView(View):
    """Render a form on GET and processes it on POST."""
    def get(self, request, *args, **kwargs):
        """Handle GET requests: instantiate a blank version of the form."""
        return self.render_to_response(self.get_context_data())

In turn, get_context_data adds a keyword argument with key form if it is not already present in **kwargs:

class FormMixin(ContextMixin):
...
    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)

So CreateView renders a Response with a context that has a 'form' key and a value ponting to the ModelForm.

A.G.
  • 37
  • 8