如果只是修改widget的默认属性可以采用如下方法:
from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) # change a widget attribute: self.fields['user_permissions'].widget.attrs["size"] = 5 class Meta: model = User
而如果要将默认的widget替换成其他的也很简单,只需要重新定义一个同名字段即可:
from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): memo = forms.CharField(label='备注',widget=forms.Textarea({'style':'width:240px'}),required=False) class Meta: model = User
当然,样式相关的内容还是要放到template才合适,但从上边代码也说明了如何改变widget的同时,修改widget属性。
另一种更加简洁的方法如下:
from django.forms import ModelForm, Textarea class UserForm(ModelForm): class Meta: model = User widgets = { ’memo’: Textarea(attrs={’cols’: 80, ’rows’: 20}), }