2012-10-28 107 views
0

我現在有模型,看起來像這樣動態相關對象的Django形式

class Lg(models.Model): 
    name = models.CharField(max_length = 50,choices = LG_CHOICES,unique = True) 

class State(models.Model): 
    name = models.CharField(max_length = 50,choices = STATE_CHOICES,unique = True) 
    lg = models.ManyToManyField(Lg,related_name ='State_Lg',blank= True,null = True) 

class AddPlaceForm(forms.Form): 
    house_number = forms.IntegerField() 
    street_name = forms.CharField() 
    area = forms.CharField() 
    city = forms.CharField() 
    lg = forms.ChoiceField(choices = Lg.objects.none()) 

    def __init__(self,state_id,*args,**kwargs): 
     super(GenericPropertyForm,self).__init__(self,*args,**kwargs) 
     self.fields['lg'] = forms.ChoiceField(choices=list(State.objects.get(id = state_id).lg.select_related())) 

我希望用戶在狀態ID通過這樣從form = AddPlaceForm(state_id)

任何一個可以請幫助視圖與此

+0

你究竟想要達到什麼目的? –

回答

0

在你看來代碼:

form = AddPlaceForm(state_id=state_id} 

形式

def __init__(self, *args, **kwargs): 
    state_id = kwargs.pop('state_id', None) 
    super(AddPlaceForm, self).__init__(*args, **kwargs) 
    self.fields['lg'] = forms.ChoiceField(choices = ((lg.id, lg.name) for lg in State.lg.filter(id=state_id)) 
+0

謝謝,但你還沒有告訴我什麼我的LG字段將看起來像 – user1711168

+0

你沒有問。 –

+0

@DanielRoseman lg字段將如何和感謝其他任何人都可以給一個手謝謝 – user1711168