开发者

How do I initialize a ForeignKey ModelChoiceField in Django?

开发者 https://www.devze.com 2023-02-28 13:54 出处:网络
This must be in the Django docs somewhere but I can\'t seem to find it. Say I have the following models:

This must be in the Django docs somewhere but I can't seem to find it.

Say I have the following models:

models.py

class MyModel(models.Model):
    name = models.CharField(max_length=15)

class MyOtherModel(models.Model):
    title = models.CharField(max_length=50)
    my_model = models.ForeignKey(MyModel)

And I create a form where I change the background color of the Select widget:

forms.py

class MyOtherModelForm(ModelForm):
    my_model=ModelChoiceField(queryset=MyModel.objects.all())

    class Meta:
        model = MyOther开发者_如何学GoModel

    def __init__(self, *args, **kwargs):
        super(MyOtherModelForm, self).__init__(*args, **kwargs)
        self.fields['my_model'].widget = Select(attrs={'style':'background_color:#F5F8EC'})

Everything works fine until the background color code is added. As soon as I add that line, I get a colored but unpopulated select widget appearing. I assume this is because once I specify some aspect of the widget's behavior, Django is looking for everything to be specified.

So how do I tell it to use the values from MyModel to populate the Select widget?


Take a look at Overriding the default field types or widgets. Based on this I would try the following.

from django.forms import ModelForm, Select

class MyOtherModelForm(ModelForm):
    my_model=ModelChoiceField(queryset=MyModel.objects.all(), widget=Select(attrs={'style':'background_color:#F5F8EC'}))

    class Meta:
        model = MyOtherModel

Also adding self.fields['my_model'].queryset = MyModel.objects.all() to your init might also work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号