[英]Django admin removes selected choice in ModelChoiceField on edit?
我在自己编写了自定义表单的管理代码中使用admin.TabularInline
。
class RateCardForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=models.Category.objects.all(), label='Category')
class Meta:
model = models.RateCard
fields = ('category')
class RateCardInline(admin.TabularInline):
model = models.RateCard
form = RateCardForm
extra = 3
问题在于,保存模型实例后,每当我编辑模型实例时,它都会删除预先选择的选项,而我将不得不再次选择该选项。 关于如何阻止它的任何想法?
同样对于ModelChoiceField
如果我没有指定标签,那么它将在管理页面上显示为None
,但是我不需要为admin.StackedInline
指定它。
要预先选择当前选择的类别实例,可以通过在ModelForm
上重写__init__()
来将其主键设置为字段的initial
值:
class RateCardForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=models.Category.objects.all(), label='Category')
class Meta:
model = models.RateCard
fields = ('category')
def __init__(self, *args, **kwargs):
super(RateCardForm, self).__init__(*args, **kwargs)
instance = kwargs.get('instance')
# Instance will be None for the empty extra rows.
if instance:
selected_pk = # query the primary key of the currently selected category here
self.fields['category'].initial = selected_pk
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.