简体   繁体   中英

Override the Style of Form templates in Django

I am new to django, I am building a form on django and found the built in forms django and implement this.

From the django documentation, it says that form.subject will put a <input type="text"> in it. But what if i want to change the properties of this input element such as height, font, text, width etc. how would do this.

{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.subject.errors }}
    <label for="{{ form.subject.id_for_label }}">Email subject:</label>
    {{ form.subject }}
</div>
<div class="fieldWrapper">
    {{ form.message.errors }}
    <label for="{{ form.message.id_for_label }}">Your message:</label>
    {{ form.message }}
</div>
<div class="fieldWrapper">
    {{ form.sender.errors }}
    <label for="{{ form.sender.id_for_label }}">Your email address:</label>
    {{ form.sender }}
</div>
<div class="fieldWrapper">
    {{ form.cc_myself.errors }}
    <label for="{{ form.cc_myself.id_for_label }}">CC yourself?</label>
    {{ form.cc_myself }}
</div>

use jquery for this.

each django form element has its unique id. use that id for applying the css properties using jquery.

access form element using id.

$('#id_subject').addClass('form-group'); #  formgroup is a bootstrap class.
 or 
$('#id_subject').css('height', '10px');

apply any css property you want here. this properties should get applied once the page is loaded ie on document.ready in jquery.

As pointed in the documentation you can add css classes:

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

Assuming you are familiar with css, you can apply styles to that field now.

There is a way to style all the widgets, but it requires better knowledge about python and django in general.

Another alternative is to use some django app that allows this, like crispy-forms or floppy-forms

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