2010-08-05 84 views
110

我在嘗試瞭解如何在django中創建動態選擇字段時遇到了一些麻煩。我有一個模型,設立類似:創建動態選擇字段

class rider(models.Model): 
    user = models.ForeignKey(User) 
    waypoint = models.ManyToManyField(Waypoint) 

class Waypoint(models.Model): 
    lat = models.FloatField() 
    lng = models.FloatField() 

我想要做的就是創建一個選擇字段衛生組織值與車手(這將是人登錄)相關的航點。

目前我重寫的init在我的形式像這樣:

class waypointForm(forms.Form): 
    def __init__(self, *args, **kwargs): 
      super(joinTripForm, self).__init__(*args, **kwargs) 
      self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.all()]) 

不過這些都不會是列表中的所有航點,他們沒有與任何特定的車手有關。有任何想法嗎?謝謝。

回答

163

可以由用戶從您的視圖傳遞到窗體初始化

class waypointForm(forms.Form): 
    def __init__(self, user, *args, **kwargs): 
     super(waypointForm, self).__init__(*args, **kwargs) 
     self.fields['waypoints'] = forms.ChoiceField(
      choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)] 
     ) 

而發起的形式傳遞用戶

form = waypointForm(user) 

模型形式的情況下,過濾航點

​​
+16

使用ModelChoiceField是否它是ModelForm - 它也適用於普通形式。 – 2010-08-06 08:02:21

+8

當你想要獲取請求數據時,你會做什麼? waypointForm(request.POST)不會在第一個驗證,因爲要驗證的數據不再存在。 – Breedly 2013-12-20 18:48:15

+1

@Ashok在這種情況下,CheckboxSelectMultiple小部件如何使用?特別是對於模型。 – wasabigeek 2015-08-14 18:22:24

8

有問題的內置解決方案:ModelChoiceField

通常,當您需要創建/更改數據庫對象時,嘗試使用ModelForm總是值得的。在95%的情況下工作,它比創建自己的實施更清潔。

4

如何在初始化時將騎手實例傳遞給窗體?

class WaypointForm(forms.Form): 
    def __init__(self, rider, *args, **kwargs): 
     super(joinTripForm, self).__init__(*args, **kwargs) 
     qs = rider.Waypoint_set.all() 
     self.fields['waypoints'] = forms.ChoiceField(choices=[(o.id, str(o)) for o in qs]) 

# In view: 
rider = request.user 
form = WaypointForm(rider) 
7

的問題是,當你在一個更新請求做

def __init__(self, user, *args, **kwargs): 
    super(waypointForm, self).__init__(*args, **kwargs) 
    self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)]) 

,以前的值會丟了!

1

正如Breedly和Liang所指出的,Ashok的解決方案將阻止您在發佈表單時獲得選擇值。

略有不同,但仍然不完善,方法來解決,這將是:

class waypointForm(forms.Form): 
    def __init__(self, user, *args, **kwargs): 
     self.base_fields['waypoints'].choices = self._do_the_choicy_thing() 
     super(waypointForm, self).__init__(*args, **kwargs) 

這可能會導致一些併發的問題,雖然。

0

在正常選擇字段下的工作解決方案。 我的問題是,每個用戶都有自己的基於少數條件的CUSTOM選擇字段選項。

class SupportForm(BaseForm): 

    affiliated = ChoiceField(required=False, label='Fieldname', choices=[], widget=Select(attrs={'onchange': 'sysAdminCheck();'})) 

    def __init__(self, *args, **kwargs): 

     self.request = kwargs.pop('request', None) 
     grid_id = get_user_from_request(self.request) 
     for l in get_all_choices().filter(user=user_id): 
      admin = 'y' if l in self.core else 'n' 
      choice = (('%s_%s' % (l.name, admin)), ('%s' % l.name)) 
      self.affiliated_choices.append(choice) 
     super(SupportForm, self).__init__(*args, **kwargs) 
     self.fields['affiliated'].choices = self.affiliated_choice