如何更改Inlines类中字段的选择?我不能在Inlines中使用formfield_for_choice_field,那么使用什么? 我必须在管理员中生成它,因为我需要传递请求。
答案 0 :(得分:4)
如果您的字段是具有choices属性的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)
祝你好运
答案 1 :(得分: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
答案 2 :(得分:1)
在我的情况下,必须填写表格选项,希望帮助任何人。
# 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)