I would like to have a Django form field render as:
<input type="text" name="username" required>
but when I try username.widget.attrs['required'] = ''
I get something like:
<input type="text" name="username" required="">
Is there a way in which the standalone HTML5 attributes like required
can be shown in the resulting HTML form?
I am using Django 1.6 on Python 2.6, for what it's worth.
You need to define the required
attribute in a valid format.
username.widget.attrs['required'] = 'required'
Take a look here for more details: https://stackoverflow.com/a/3012975/1566605
@mariodev is correct. If you want a more elegant way to do this, refer to https://stackoverflow.com/a/37738828/2812260 (relevant part copied below):
If you really want to write elegant, DRY code, you should make a base form class that dynamically looks for all your required fields and modifies their widget required attribute for you (you can name it whatever you wish, but "BaseForm" seems apt):
from django.forms import ModelForm
class BaseForm(ModelForm):
def __init__(self, *args, **kwargs):
super(BaseForm, self).__init__(*args, **kwargs)
for bound_field in self:
if hasattr(bound_field, "field") and bound_field.field.required:
bound_field.field.widget.attrs["required"] = "required"
And then have all your Form objects descend from it:
class UserForm(BaseForm):
class Meta:
model = User
fields = []
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
email = forms.EmailField(required=True, max_length=100)
If you want a declarative option on a per-form rather than a per-model basis this was my solution:
from django import forms
class RequiredFieldsModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RequiredFieldsModelForm, self).__init__(*args, **kwargs)
for bound_field in self:
if (
hasattr(bound_field, "field") and
bound_field.name in self.Meta.required_fields
):
bound_field.field.widget.attrs["required"] = "required"
# Your forms
class UserForm(RequiredFieldsModelForm):
class Meta:
required_fields = ['username']
model = User
Just set required attribute to widget like this:
self.fields['field_name'].widget = forms.TextInput(attrs={'required':'required'})
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.