346๐
Look at the widgets documentation. Basically it would look like:
q = forms.CharField(label='search',
widget=forms.TextInput(attrs={'placeholder': 'Search'}))
More writing, yes, but the separation allows for better abstraction of more complicated cases.
You can also declare a widgets
attribute containing a <field name> => <widget instance>
mapping directly on the Meta
of your ModelForm
sub-class.
72๐
For a ModelForm, you can use the Meta class thus:
from django import forms
from .models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
widgets = {
'name': forms.TextInput(attrs={'placeholder': 'Name'}),
'description': forms.Textarea(
attrs={'placeholder': 'Enter description here'}),
}
- [Django]-Resource temporarily unavailable using uwsgi + nginx
- [Django]-Sending post data from angularjs to django as JSON and not as raw content
- [Django]-How to revert the last migration?
57๐
The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:
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 also allows the placeholder to depend on the instance for ModelForms with instance specified.
- [Django]-Embedding JSON objects in script tags
- [Django]-Django, Models & Forms: replace "This field is required" message
- [Django]-What is related_name used for?
29๐
Great question. There are three solutions I know about:
Solution #1
Replace the default widget.
class SearchForm(forms.Form):
q = forms.CharField(
label='Search',
widget=forms.TextInput(attrs={'placeholder': 'Search'})
)
Solution #2
Customize the default widget. If youโre using the same widget that the field usually uses then you can simply customize that one instead of instantiating an entirely new one.
class SearchForm(forms.Form):
q = forms.CharField(label='Search')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['q'].widget.attrs.update({'placeholder': 'Search'})
Solution #3
Finally, if youโre working with a model form then (in addition to the previous two solutions) you have the option to specify a custom widget for a field by setting the widgets
attribute of the inner Meta
class.
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
widgets = {
'body': forms.Textarea(attrs={'cols': 80, 'rows': 20})
}
- [Django]-Django โ how to visualize signals and save overrides?
- [Django]-How do I use django rest framework to send a file in response?
- [Django]-Allowing RabbitMQ-Server Connections
21๐
You can use this code to add placeholder attr for every TextInput field in you form. Text for placeholders will be taken from model field labels.
class PlaceholderDemoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PlaceholderDemoForm, self).__init__(*args, **kwargs)
for field_name in self.fields:
field = self.fields.get(field_name)
if field:
if type(field.widget) in (forms.TextInput, forms.DateInput):
field.widget = forms.TextInput(attrs={'placeholder': field.label})
class Meta:
model = DemoModel
- [Django]-Django: Multiple forms possible when using FormView?
- [Django]-Adding to the "constructor" of a django model
- [Django]-Django Footer and header on each page with {% extends }
5๐
Most of the time I just wish to have all placeholders equal to the verbose name of the field defined in my models
Iโve added a mixin to easily do this to any form that I create,
class ProductForm(PlaceholderMixin, ModelForm):
class Meta:
model = Product
fields = ('name', 'description', 'location', 'store')
And
class PlaceholderMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
field_names = [field_name for field_name, _ in self.fields.items()]
for field_name in field_names:
field = self.fields.get(field_name)
field.widget.attrs.update({'placeholder': field.label})
- [Django]-Django + Ajax
- [Django]-Django celery task: Newly created model DoesNotExist
- [Django]-In a django model custom save() method, how should you identify a new object?
2๐
Itโs undesirable to have to know how to instantiate a widget when you just want to override its placeholder.
q = forms.CharField(label='search')
...
q.widget.attrs['placeholder'] = "Search"
- [Django]-How do I run tests against a Django data migration?
- [Django]-Why is logged_out.html not overriding in django registration?
- [Django]-Django โ No module named _sqlite3
2๐
class FormClass(forms.ModelForm):
class Meta:
model = Book
fields = '__all__'
widgets = {
'field_name': forms.TextInput(attrs={'placeholder': 'Type placeholder text here..'}),
}
- [Django]-How do I clone a Django model instance object and save it to the database?
- [Django]-Sending HTML email in django
- [Django]-Has Django served an excess of 100k daily visits?
0๐
After looking at your method, I used this method to solve it.
class Register(forms.Form):
username = forms.CharField(label='็จๆทๅ', max_length=32)
email = forms.EmailField(label='้ฎ็ฎฑ', max_length=64)
password = forms.CharField(label="ๅฏ็ ", min_length=6, max_length=16)
captcha = forms.CharField(label="้ช่ฏ็ ", max_length=4)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name in self.fields:
field = self.fields.get(field_name)
self.fields[field_name].widget.attrs.update({
"placeholder": field.label,
'class': "input-control"
})
- [Django]-Django 1.5b1: executing django-admin.py causes "No module named settings" error
- [Django]-Why does Django's render() function need the "request" argument?
- [Django]-Django form: what is the best way to modify posted data before validating?