Increase CharField Width in Django Forms

2020-08-10 08:20发布

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?

2条回答
别忘想泡老子
2楼-- · 2020-08-10 08:42

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}))
查看更多
冷血范
3楼-- · 2020-08-10 08:52

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'})}
    }
查看更多
登录 后发表回答