34👍
✅
See the documentation
class AuthorForm(ModelForm):
class Meta:
model = Author
widgets = {
'name': TextInput(attrs={'placeholder': 'name'}),
}
You could always create your own widget that derives from TextInput and includes the placeholder attribute, and use the widgets dictionary to simply map fields to your new widget without specifying the placeholder attribute for every field.
20👍
Personally I prefer to use this method:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or 'email@address.nl'
It required more code if you don’t have __init__
yet, but you don’t need to specify the widget.
👤Mark
- [Django]-Accessing a dict by variable in Django templates?
- [Django]-Django: how to do calculation inside the template html page?
- [Django]-Django auto_now and auto_now_add
0👍
Here is a reusable mixin for Form classes based on @Mark’s method
from django.core.exceptions import ImproperlyConfigured
class PlaceholderMixin():
def placeholder_setup(self):
if not hasattr(self.Meta, 'placeholders'):
raise ImproperlyConfigured('Meta class must have a placeholders dict')
for field, placeholder in self.Meta.placeholders.items():
self.fields[field].widget.attrs['placeholder'] = placeholder
To use it, add it to a Form class and define placeholders in the Meta class:
class MyForm(forms.ModelForm, PlaceholderMixin):
class Meta:
model = MyModel
fields = [ 'name', 'description', 'choices' ]
placeholders = {
'name': 'your name',
'description': 'describe yourself'
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.placeholder_setup()
- [Django]-How to see if a value or object is in a QuerySet field
- [Django]-Visual studio code breakpoint set to grey color & not working.error(may be excluded because of "justMyCode" option)
- [Django]-Python coverage badges, how to get them?
Source:stackexchange.com