Home > Mobile >  How can I add required attribute?
How can I add required attribute?

Time:07-12

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;'})
        }
        

    

CodePudding user response:

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.

CodePudding user response:

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"

CodePudding user response:

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

CodePudding user response:

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

  • Related