Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Producing the right HTML semantics with Django

Tags:

django

I usually keep it simple and use the following form syntax in my templates:

<div>
       <div>{{form.title.label}}:</div>
       <div>{{form.title}}</div>
</div>

The problem with this approach is the bad semantic in the html output.

<div>
    <div>Title:</div>
    <div><input id="id_form-title" type="text" maxlength="30" name="form-title"></div>
</div>

Correct should be:

<div>
    <label for="id_form-title">Title</label>
    <input id="id_form-title" type="text" maxlength="30" name="form-title">
</div>

Is there a django build-in tag to do this automatically for me, or do I have to do it manually myself like this?

<div>
    <label for="id_form-title">{{form.title.label}}</label>
    {{form.title}}
</div>
like image 433
Houman Avatar asked Nov 20 '12 13:11

Houman


2 Answers

It is indeed annoying that outputting fields one by one doesn't give you automatic access to a properly-constructed label element - doing form.as_p will correctly produce the fields plus labels, but you give up all control over the form layout.

You can build up the label tag using the field information fairly easily though:

<label for="{{ field.auto_id }}">{{ field.label }}</label>
{{ field }}

You can put this in a template tag for easier reuse.

Don't forget to also add {{ field.errors }} to display the errors associated with each field.

like image 178
Daniel Roseman Avatar answered Sep 22 '22 09:09

Daniel Roseman


using label_tag should give you properly constructed label tag. So instead of just {{form.title.label}} you should use {{form.title.label_tag}} and it will result in the desired html

like image 24
Rohan Avatar answered Sep 23 '22 09:09

Rohan