2

In the Model I set the maxlength of the field:

short_description = models.CharField(max_length=405)

In the ModelForm in the widget attributes I set minlength an maxlength:

class ItemModelForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ['name', 'short_description', 'description']
    widgets = {
            'name': TextInputWidget(attrs={'placeholder': 'Name*'}),
        'short_description': TextareaWidget(attrs={'minlength': 200, 'maxlength': 400}) 

}

The issue in the HTML the minlegth is from the widget, but maxlength is still taken from the model(405 instead of 400).

I want the widget attribute to overwrite the model attribute.

user3541631
  • 3,686
  • 8
  • 48
  • 115

2 Answers2

5

The widgets property in the Meta class modify only, well, the widgets, not the field attributes itself. What you have to do is redefine your model form field.

class ItemModelForm(forms.ModelForm):
    short_description = forms.CharField(max_length=400, min_length=200, widget=TextareaWidget())

    class Meta:
        model = Item
        fields = ['name', 'short_description', 'description']
        widgets = {
            'name': TextInputWidget(attrs={'placeholder': 'Name*'}),
        }
Vitor Freitas
  • 3,550
  • 1
  • 24
  • 35
  • actually it added minlenght (but this didn't existed on the model) – user3541631 Feb 16 '18 at 09:37
  • But you added the minlength youself in your code snippet, I just replicated what you had: `'short_description': TextareaWidget(attrs={'minlength': 200, 'maxlength': 400}) `. If you don't need the `min_length`, just remove it: `short_description = forms.CharField(max_length=400, widget=TextareaWidget())` – Vitor Freitas Feb 16 '18 at 09:39
1
class ItemModelForm(forms.ModelForm):
    short_description = forms.CharField(
        max_length = 400,
        min_length = 200,
        widget=forms.Textarea(
        )
    )

    class Meta:
        model = Item
        fields = ['name', 'short_description', 'description']
        widgets = {
        'name': TextInputWidget(attrs={'placeholder': 'Name*'}),
        }
Rohan Baddi
  • 479
  • 2
  • 12