Mossaddak
Mossaddak

Reputation: 421

How can I add required attribute?

I would like to add the required attribute in the product_title field. How can I do It?

class add_product_info(forms.ModelForm):
    product_desc = RichTextField()

    class Meta:
        model = Products
        fields = ('product_title')

        labels = {'product_title':'Title'}

        widgets = {
            'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'})
        }
        

    

Upvotes: 0

Views: 589

Answers (4)

Onyilimba
Onyilimba

Reputation: 1217

if you want to add to your template you can use django widget tweaks

{% load widget_tweaks %}

<!-- add 2 extra css classes to field element -->
{{ form.title|append_attr:"class:css_class_1 css_class_2" }}

django_widget_tweaks

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477641

Use required in the field specifications. This will also enforce this at form level, so the Django form will reject the form in case the field is not filled in:

class ProductInfoForm(forms.ModelForm):
    product_desc = RichTextField(required=True)

    class Meta:
        model = Products
        fields = ('product_title',)
        labels = {'product_title':'Title'}
        widgets = {
            'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'})
        }

Note: Forms in Django are written in PascalCase, not snake_case, so you might want to rename the model from add_product_info to ProductInfoForm.

Upvotes: 4

NixonSparrow
NixonSparrow

Reputation: 6388

You can slightly manipulate existing fields in __init__ method. In this way you can automatically add that attribute.

class BaseForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__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"

Upvotes: 2

JanMalte
JanMalte

Reputation: 1060

Just the same way like you added the style or class attribute:

class add_product_info(forms.ModelForm):
    product_desc = RichTextField()

    class Meta:
        model = Products
        fields = ('product_title')
        labels = {'product_title':'Title'}
        widgets = {
            'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;', 'required': True})
        }

Upvotes: 1

Related Questions