创build一个dynamicselect字段

我在尝试了解如何在django中创builddynamicselect字段时遇到了一些麻烦。 我有一个模型设置类似于:

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

我想要做的是创build一个select字段whos值是与骑手(这将是login的人)相关的航点。

目前我在我的forms覆盖初始化像这样:

 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()]) 

但是,所有这些都是列出所有的路标,它们并不与任何特定的骑手相关联。 有任何想法吗? 谢谢。

您可以通过将用户传递给表单init来过滤航点

 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)] ) 

在发起表单的同时从您的视angular传递用户

 form = waypointForm(user) 

在模型的情况下

 class waypointForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(waypointForm, self).__init__(*args, **kwargs) self.fields['waypoints'] = forms.ModelChoiceField( queryset=Waypoint.objects.filter(user=user) ) class Meta: model = Waypoint 

有问题的内置解决scheme: ModelChoiceField 。

通常,当您需要创build/更改数据库对象时,总是值得使用ModelForm 。 在95%的情况下工作,它比创build自己的实施更清洁。

问题是当你这样做

 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)]) 

在更新请求中,以前的值将会丢失!

如何在初始化时将骑手实例传递给窗体?

 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) 

正如Breedly和Liang所指出的,Ashok的解决scheme将阻止您在发布表单时获得select的价值。

一个稍微不同的,但仍然不完美的方法来解决这个问题将是:

 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) 

但这可能会导致一些并发问题。

在正常的select领域下的工作解决scheme。 我的问题是,每个用户都有自己的CUSTOM choicefield选项基于less数条件。

 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