How do I add a placeholder on a CharField in Django?

前端 未结 9 1337
执笔经年
执笔经年 2020-11-28 19:53

Take this very simple form for example:

class SearchForm(Form):
    q = forms.CharField(label=\'search\')

This gets rendered in the templat

相关标签:
9条回答
  • 2020-11-28 20:06

    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'}),
            }
    
    0 讨论(0)
  • 2020-11-28 20:09

    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.

    0 讨论(0)
  • 2020-11-28 20:13

    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.

    0 讨论(0)
  • 2020-11-28 20:17

    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"
    
    0 讨论(0)
  • 2020-11-28 20:18
    class FormClass(forms.ModelForm):
        class Meta:
            model = Book
            fields = '__all__'
            widgets = {
                'field_name': forms.TextInput(attrs={'placeholder': 'Type placeholder text here..'}),
            }
    
    0 讨论(0)
  • 2020-11-28 20: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
    
    0 讨论(0)
提交回复
热议问题