简体   繁体   中英

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.

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 .

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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