2011-11-19 50 views
0

我有这些模型:显示的ModelForm填充组合框由一个PK过滤

class LocationType(models.Model): 
    Name=models.CharField(max_length=50) 
    Description=models.CharField(max_length=200) 

class Location(models.Model): 
    Name=models.CharField(max_length=100) 
    ParentCode=models.BigIntegerField() 
    LocationType=models.ForeignKey(LocationType) 

class Visa(models.Model): 
    Country=models.ForeignKey(Location) 
    Price=models.CharField(max_length=12) 
    ActionUser=models.ForeignKey(User,editable=False) 

forms.py我有这样的:

class VisaForm(ModelForm): 
    class Meta: 
     model=Visa 

我要显示的位置的组合框(为Visa模式的国家/地区)以签证形式提供,并由特殊的LocationType过滤。

想象一下,我有一个LocationType价值name=Country,pk=1。在visa_form我想显示Location s列表,但不是全部。只需地址为locationType_id=1

如何填写此组合框并以签证形式显示?

回答

1

你应该可以使用django ChoiceField。它需要一个arg choices,您可以将它设置为元组类型(最后可以为元组创建列表,因为您可能会以列表开始)。您只需根据名称=国家和pk = 1筛选对象,然后CHOICES(如果您想为您的变量命名),并设置choices = CHOICES

我希望有帮助。

只要将ChoicesField添加到ModelForm,您就可以从中继承并添加该字段。

+2

也许['ModelChoiceField'](https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield)会更适用于有问题的情况。 –

+0

感谢U everybodey,我这样做,它的工作原理:在__init__ self.fields [“Country”]。queryset = Location.objects.filter(LocationTypeCode__id = locationType.id) –

3

东西上的行:

class VisaForm(ModelForm): 
    def __init__(self, location_type, *args, **kwargs): 
     super(VisaForm, self).__init__(*args, **kwargs) 
     self.fields['Country'] = forms.ModelChoiceField(queryset=Location.objects.filter(LocationType=location_type)) 

    class Meta: 
     model=Visa