简体   繁体   English

Django管理员在编辑时会删除ModelChoiceField中的选定选项吗?

[英]Django admin removes selected choice in ModelChoiceField on edit?

I'm using admin.TabularInline in my admin code for which I've made a custom form. 我在自己编写了自定义表单的管理代码中使用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

The problem is that after I've saved my model instance, whenever I edit the model instance, it would remove the pre-selected choice and I'll have to select the choice again. 问题在于,保存模型实例后,每当我编辑模型实例时,它都会删除预先选择的选项,而我将不得不再次选择该选项。 Any ideas as to how to stop it? 关于如何阻止它的任何想法?

Also for ModelChoiceField if I don't specify the label, then it would come up as None on admin page, but I don't need to specify it for admin.StackedInline . 同样对于ModelChoiceField如果我没有指定标签,那么它将在管理页面上显示为None ,但是我不需要为admin.StackedInline指定它。

To preselect the currently selected category instance you can set its primary key to the field's initial value by overriding __init__() on the ModelForm : 要预先选择当前选择的类别实例,可以通过在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM