2010-08-05 75 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