In Django form, custom SelectField and SelectMultipleField

后端 未结 5 1636
野趣味
野趣味 2021-01-02 16:11

I am using Django everyday now for three month and it is really great. Fast web application development.

I have still one thing that I cannot do exactly how I want t

5条回答
  •  青春惊慌失措
    2021-01-02 16:38

    You should not mess with form fields for adding some custom attributes to the rendered html tag. But you should subclass and add a these to the Widget.

    From the docs: customizing-widget-instances

    You can submit attrs dictionary to the form Widgets, that render as attributes on the output form widgets.

    class CommentForm(forms.Form):
        name = forms.CharField(
                    widget=forms.TextInput(attrs={'class':'special'}))
        url = forms.URLField()
        comment = forms.CharField(
                   widget=forms.TextInput(attrs={'size':'40'}))
    Django will then include the extra attributes in the rendered output:
    
    >>> f = CommentForm(auto_id=False)
    >>> f.as_table()
    Name:
    Url:
    Comment:
    

提交回复
热议问题