KhoPhi
KhoPhi

Reputation: 9517

Render form without tags django

{% for fields in form %}
   {{ field.label }}
   {{ field }}
{% endfor %}

The {{ field }} will render something similar to:

<input type="text" id="something_id" .../>

Is there a way I can render a field without having to let it wrap it in a tag? So for instance, I render a field and I get (without the input tag):

type='text' id='_something_id'

In this case, I can go ahead to manually add custom classes as and when and where I want like:

<input {{ field }} class='class class-again' required autocomplete='off' />

Is there a way I can do that in Django, render a field without it wrapped in the element?

Obviously, such a hard way of formatting can be tiring if working on tons of fields making such an approach impractical. In my case, I'm just wanting to tailor some css to just two fields, and having to go through Django Forms, or template tags etc, I find the process lengthy

Upvotes: 2

Views: 1824

Answers (2)

zvyn
zvyn

Reputation: 716

You can do this if you know the input type:

{% for field in form %}
    {{ field.label_tag }}
    <input type="text" id="{{ field.id_for_label }}" name="{{ field.html_name }}" value="{{ field.value }}"/>
{% endfor %}

If you have different input types you could still go through the fields manually instead of iterating over them (using their name, eg. form.username).

However in most cases it is better to do those things on the backend using the widget API like this:

name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))

Upvotes: 1

Gocht
Gocht

Reputation: 10256

It is possible. You could write your own HTML code, you know that Django assigns id and name attributes with a format, like: id='something_id'. The name attribute is the important one, you should make sure it is the same that Django would assigns.

Another option is this:

# I will assume you have a field named something
something = forms.CharField(widget=forms.TextInput(attrs={'class':'class class-again''}))

This should do what you need. I hope this helps.

Upvotes: 0

Related Questions