Increase CharField Width in Django Forms

2020-08-10 07:53发布

问题:

I am extending UserCreationForm and have added

username=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'size':'80'}))

but the username field width does not change. How can I increase it?

回答1:

Try specifying widgets in the form, as in the following example:

models.py

class Photo(models.Model):
    caption = models.CharField(max_length=80)

admin.py

class PhotoAdmin(admin.ModelAdmin):
    list_display = (u'preview', u'caption')
    search_fields = (u'caption')
    form = forms.PhotoAdminForm

forms.py

class PhotoAdminForm(forms.ModelForm):
    class Meta:
        widgets = { 'caption': forms.TextInput(attrs={'size': 80})}

As alternative, you can use the following:

forms.py

class PhotoAdminForm(forms.ModelForm):
    caption = forms.CharField(widget=forms.TextInput(attrs={'size':80}))


回答2:

Since 1.7 you can solve it like this:

admin.py

class PhotoAdmin(admin.ModelAdmin):
    list_display = (u'preview', u'caption')
    search_fields = (u'caption')
    formfield_overrides = {
        models.CharField: {'widget': TextInput(attrs={'size': '80'})}
    }