6

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.

0

4 Answers 4

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

It would be useful to explain where this line should be added to those that are learning Django.
8

@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)

Comments

1

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

Comments

0

Just set required attribute to widget like this:

self.fields['field_name'].widget = forms.TextInput(attrs={'required':'required'})

1 Comment

You should place this in init method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.