Django ModelChoiceField初始值不起作用

时间:2019-04-18 13:50:27

标签: python django django-models django-forms

我有以下表格:

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']

,我想设置shelf的初始值。我已经尝试过了,但是根本不起作用。

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

除了使用initial kwarg之外,我无法通过解决方案在网上找到任何东西,所以我有点迷失了。使用__init__函数过滤查询集是否与我有关?

2 个答案:

答案 0 :(得分:1)

您可以尝试将其添加到 init 函数中:

<myproject:CustomListControl
                                x:Name="listDisplay"
                                HorizontalAlignment="Stretch"
                                VerticalAlignment="Stretch"                                
                                IsDropDownOpen="{Binding Path=IsDDOpen, Mode=TwoWay}"
                                SelectedItem="{Binding Path=SelectedValue, Mode=TwoWay}">
                                <i:Interaction.Triggers>
                                    <i:EventTrigger EventName="MouseLeftButtonUp">
                                        <interactivity:InvokeCommandAction
                                            AutoEnable="False"
                                            Command="{Binding}"/>
                                    </i:EventTrigger>
                                </i:Interaction.Triggers>
                            </myproject:CustomListControl>

其中YOUR_INITIAL_VALUE是您要用来初始化货架的值。

答案 1 :(得分:0)

对我有用的是在 models.py 中放置一个默认参数

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

相关问题