简体   繁体   中英

Django ModelChoiceField initial value not working

I've got the following form:

class AddGameForm(forms.ModelForm):
    notes = forms.CharField(widget=forms.Textarea)
    shelf = forms.ModelChoiceField(queryset=Shelf.objects.all())

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(AddGameForm, self).__init__(*args, **kwargs)
        self.fields['shelf'].queryset = Shelf.objects.filter(owner=self.user)

    class Meta:
        model = Game
        fields = ['name', 'status', 'hours', 'minutes', 'platform', 'notes', 'shelf']

and I want to set the initial value of shelf . I've tried this, but it doesn't work, at all.

shelf = GameShelfJunction.objects.filter(game_id=game).first()
form = AddGameForm(instance=game, initial={'shelf': shelf.pk}, user=request.user)

I can't find anything online with a solution other than using the initial kwarg, so I'm kind of lost. Does this have to do with me using the __init__ function to filter the queryset?

you can try to add this inside init function:

self.initial['shelf'] = YOUR_INITIAL_VALUE

where YOUR_INITIAL_VALUE is the value you want shelf is initialized with.

What worked for me was putting a default-argument in models.py

# models.py
shelf =  models.ForeignKey(Shelf.objects.all(), on_delete=models.SET_NULL, null=True, default='pk_you_want_as_initial')

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