I have a tags CharField
with a maxlength of 300, but I need to reserve 100 characters of that for default inputs, but I want users to be able to set the remaining 200 characters via an input text box. My plant to do this was to set the maxlength of the charfield in the model to 300, and in my form make a widget for the input limiting the user's input to 200 characters.
However, I've done some testing and find that I can't change the input field's max length from the maxlength of the charfield itself. Does anyone know how ot do this?
models.py
class Video(models.Model):
title = models.CharField(max_length=50)
tags = models.CharField(max_length=200)
form.py
class VideoForm(forms.ModelForm):
class Meta:
model=Video
fields=['title','description','authorId','tags','video','thumbnail']
#a widget is django's representation of an html input element
widgets = {
'tags': forms.Textarea(attrs={'cols': 80, 'rows': 20,'maxlength':5}),
}
The resulting html textarea of the above code is <textarea cols="80" id="id_tags" maxlength="200" name="tags" rows="20"></textarea>
, but instead I want the maxlength
to be 5.
Override the VideoForm's constructor:
class VideoForm(forms.ModelForm):
...
def __init__(self, *args, **kwargs):
super(VideoForm, self).__init__(*args, **kwargs)
self.fields['tags'].widget.attrs['maxlength'] = 5
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.