{{ theform.address }}
{{ theform.phone }}
This is what I do in my templates.
However, what if I want to add placehold开发者_如何学编程er="Username"
to the input text field? (Custom attribute)
<input type="text" name="address" id="id_address" placeholder="username"/>
Add the attrs
keyword argument to your field constructor's widget
, and include write your attribute in there:
address = forms.TextField(widget=forms.TextInput(attrs={'placeholder': 'username'}))
If you want to see it in action, take a look at django-registration's forms.py.
Alternatively, you can use the http://pypi.python.org/pypi/django-widget-tweaks app:
{% load widget_tweaks %}
...
{{ theform.address|attr:"placeholder:username" }}
In the class wherein you specify your forms, you can set the 'widgets' per each form element. The 'widget' contains information on that element's attributes, etc.
Here's an example (applies if you're creating your form through ModelForm):
class BlogEntryForm(ModelForm):
class Meta:
model = BlogEntry
fields = (
'title',
'category',
'text_entry',
'private'
)
widgets = {
'category': forms.Select(
attrs={
'class': 'form-control'
},
choices=[]
),
'title': forms.TextInput(
attrs={
'class': 'form-control',
}
),
'text_entry': forms.Textarea(
attrs={
'id': 'text-editor',
'class': 'form-control',
'rows': '17',
}
),
'private': forms.CheckboxInput(
attrs = {
'id': 'make-post-private',
'class': 'custom-control-input'
}
)
}
精彩评论