如何更改 Inlines 类中字段的选择?我不能在 Inlines 中使用 formfield_for_choice_field,那该怎么用呢?我必须在管理员中生成它,因为我需要通过请求。
问问题
2774 次
3 回答
5
如果您的字段是具有选择属性的 IntegerField 或 Charfield,您可以使用以下内容覆盖内联类中的formfield_for_choice_field方法:
class YourInline(admin.StackedInline): # or TabularInline
model = YourModelName
def formfield_for_choice_field(self, db_field, request=None, **kwargs):
if db_field.name == 'YOUR_FIELD_NAME':
kwargs['choices'] = (('', '---------'), ('1', 'Choice1'), ('2', 'Choice2'))
return db_field.formfield(**kwargs)
祝你好运
于 2012-04-18T16:43:19.030 回答
2
就我而言,必须填写表格选项,希望对任何人有所帮助。
# admin.py
class YourInlineForm(forms.ModelForm):
class Meta:
fields = '__all__'
model = YourModelName
widgets = {
'level': forms.widgets.Select(
choices = (
(0,'A'),
(1,'B'),
(2,'C'),
),
)
}
# admin.py
class YourInline(admin.StackedInline): # or TabularInline
model = YourModelName
form = YourInlineForm
def formfield_for_choice_field(self, db_field, request=None, **kwargs):
if db_field.name == 'YOUR_FIELD_NAME':
kwargs['choices'] = (('', '---------'), ('1', 'Choice1'), ('2', 'Choice2'))
return db_field.formfield(**kwargs)
于 2018-01-31T06:01:17.587 回答
1
我同意eos87的回答。然而,这只是部分解决方案。保存时,会出现验证错误,因为原始模型的选择正在用于验证。要解决该问题,请将此函数添加到您的模型中:
def clean_fields(self, exclude=None):
exclude.append('YOUR_FIELD_NAME') # we will do our own validation on this field
super(YOUR_MODEL, self).clean_fields(exclude = exclude)
value = self.YOUR_FIELD_NAME
if value and not self.validChoice(value):
msg = 'Select a valid choice. %s is not one of the available choices.'
errors = {''YOUR_FIELD_NAME'': ([msg % value])}
raise ValidationError(errors)
def validChoice(self, value):
# add your validation code here
于 2014-10-08T16:17:23.517 回答