2011-11-19 58 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