0

Django's documentation says that by creating the following form:

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

the following form will be rendered:

<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100">

Yet for some reason when I create an instance of this form and print it in my terminal I get the following.

NameForm()
print(NameForm())

<tr><th><label for="id_your_name">Your name:</label></th><td><input id="id_your_name" maxlength="100" name="your_name" type="text" /></td></tr>

The weirdest part of this is that when I send this form to my template via a context dictionary I get:

<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100">

So even though I do get what documentation states I should get, why does it render as a table prior to hitting the browser i.e. render as

<tr><th><label for="id_your_name">Your name:</label></th><td><input id="id_your_name" maxlength="100" name="your_name" type="text" /></td></tr>

in my terminal?

0

2 Answers 2

1

You can see here Outputting forms as HTML that when you directly print a form instance the default output is a <table>

But when you render the form inside a template using {{ form }}, then these table tags are omitted.

Sign up to request clarification or add additional context in comments.

2 Comments

I get that, but why? What is the motif behind this?
I'm just taking a guess here, first of all you'll never want to directly print a form instance, you'll always pass it in context dictionary. When you're directly printing a form instance, you're doing it mostly for debugging purposes. I guess the default <table> output makes it easier to use it inside an html page because most of the formatting will be taken care of by the <table> tags. And that is just a default value. You have other way to output as well.
0

As mentioned by Kartik Anand, this is just default templating of django form and there are more of them.

But if you're not satisfied with default, there is way to print it in your template as you like. Django form is an iterable and when iterating through, it will give you each field from form one by one. Each field will be of class BoundField that will allow you to get full tags for label, field and errors list.

So if you want to build plain form, you can do:

for bound_field in form:
    print(bound_field.label_tag())
    print(bound_field)
    print(bound_field.errors)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.