How do I initialize a ForeignKey ModelChoiceField in Django?
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.
精彩评论