Define css class in django Forms

前端 未结 13 841
南旧
南旧 2020-11-27 10:11

Assume I have a form

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.Boolea         


        
13条回答
  •  伪装坚强ぢ
    2020-11-27 10:24

    Expanding on the method pointed to at docs.djangoproject.com:

    class MyForm(forms.Form): 
        comment = forms.CharField(
                widget=forms.TextInput(attrs={'size':'40'}))
    

    I thought it was troublesome to have to know the native widget type for every field, and thought it funny to override the default just to put a class name on a form field. This seems to work for me:

    class MyForm(forms.Form): 
        #This instantiates the field w/ the default widget
        comment = forms.CharField()
    
        #We only override the part we care about
        comment.widget.attrs['size'] = '40'
    

    This seems a little cleaner to me.

提交回复
热议问题