这是我的一个父类
class BlogCommentForm(forms.ModelForm):
class Meta:
model = BlogComment
fields = ['user_name', 'body']
widgets = {
'user_name': forms.TextInput(attrs={
'required': 'required',
# ...还有很多其他属性
}),
'body': forms.Textarea(attrs={
'required': 'required',
# ...还有很多其他属性
}),
}这是我的子类
class SubCommentForm(BlogCommentForm):
class Meta:
# SubComment也是继承自BlogComment
model = SubComment
fields = ['user_name', 'body']
widgets = {
'user_name': forms.TextInput(attrs={
'required': 'required',
# ...还有很多其他属性
}),
'body': forms.Textarea(attrs={
'required': 'required',
# ...还有很多其他属性
}),
}现在我想简化一下代码,因为我的SubComment也是继承自BlogComment,所以对于SubCommentForm这个子类我只想让下model = SubComment,对于fields和widgets属性,我不想增加或者任何内容,请问我应该怎样做呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你可以将那2个属性忽略不写,默认会自动继承父类的东西,只是模型model哪里改成你要的模型。
两种写法:
import copy class A: class Meta: model = 'hello' fields = ['a', 'b'] widgets = {'a': 'b'} class B(A): """第一种""" dic = copy.deepcopy({ k: v for (k, v) in A.Meta.__dict__.items() if not k.startswith('__') }) dic['model'] = 'b' Meta = type('Meta', (object,), dic) class C(A): """第二种""" class Meta: model = 'c' widgets = copy.deepcopy(A.Meta.widgets) fields = copy.deepcopy(A.Meta.fields)