简体   繁体   中英

Form in django form.as_p different

what form.to_p exacly return?

I mean

this code:

            <form action="{{ action }}" method="post" enctype="multipart/form-data">
                {% csrf_token %}
                        <input type="text" name="title_field" id="form.title}}"/>
                        <input type="text" name="author_field" id="form.author }}"/>
                        {{ form.content }}
                        <input type="submit" value="Send"/>
            </form>

doesn't work, instead of this code works:

            <form action="" method="post" enctype="multipart/form-data">
                {% csrf_token %}
                {{ form.as_p }}
                <input type="submit" value="Send"/>
            </form>

Of course in the first case I can stylize in html/css specific fields..

@edit

by working I mean send forward. In first second doesn't do anything

Forms have a few optional rendering options in django: as_p, as_table, as_ul

Without any rendering options:

<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Send"/>
</form>

Will render a form that looks like this:

<form action="" method="post" enctype="multipart/form-data">
<input>
<input>
<input>
...
</form>

Adding the rendering option as_p just wraps the input fields in paragraph tags. So adding the as_p here:

<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send"/>
</form>

Will render a form that looks like this:

<form action="" method="post" enctype="multipart/form-data">
<p><input></p>
<p><input></p>
<p><input></p>
...
</form>

To see what {{ form.as_p }} outputs, you can click 'view source' in your browser and see the rendered html.

I would not recommend rendering the fields manually as in your first example. It's easy to make mistakes. For example you have forgotten the opening {{ in id="form.title}}" .

If you need to add a custom class to the input, you can do this by changing the field's widget . Alternatively, you might find crispy forms useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM