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

前端 未结 9 1338
执笔经年
执笔经年 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:21

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

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

    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"
            })
    
    0 讨论(0)
提交回复
热议问题