python - Django admin removes selected choice in ModelChoiceField on edit? -
i'm using admin.tabularinline
in admin code i've made 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 = 3
the problem after i've saved model instance, whenever edit model instance, remove pre-selected choice , i'll have select choice again. ideas how stop it?
also modelchoicefield
if don't specify label, come none
on admin page, don't need specify admin.stackedinline
.
to preselect selected category instance can set primary key field's initial
value overriding __init__()
on 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 none empty rows. if instance: selected_pk = # query primary key of selected category here self.fields['category'].initial = selected_pk
Comments
Post a Comment