ion
ion copied to clipboard
Add Character Counter to Text Fields
This would apply to text fields with a character limit (e.g. the poll description).
To do this, one would need to either:
- Create a new class right above
django.forms.ModelForm
that overridesas_table
to include a character counter when the, or - Create a new class above
django.forms.CharField
anddjango.forms.TextField
to, when initted, add a character counter to its widget.
1 would be slightly easier to implement, just import that class from utils
or something instead of the default class, but 2 would be more effictive yet "dirtier" (and harder) because it would require monkey-patching the classes for django to use the new ones internally.
Which one should we go with, or am I missing a better option?
Since we already have self.fields["description"].widget = forms.Textarea()
here, we can just change that to something like shown below and create the counter client-side using Javascript. It would still be validated server side.
class Meta:
model = Poll
exclude = [] # type: List[str]
widgets = {
'name': forms.Textarea(attrs={"data-counter": 400),
}
My issue with that solution is that is would require patching widgets for every class that requires a character counter. That may not be a bad thing though (do we want counters everywhere?).
This would probably only apply to things that already use a Textarea widget, so most of the code would already be there. I was looking for a dynamic way to set the length but I couldn't find one. I'll see if I can find something though