创建动态选择字段
我在理解如何在Django中创建一个动态选择字段时遇到了一些问题。我有一个模型大致是这样的:
class rider(models.Model):
user = models.ForeignKey(User)
waypoint = models.ManyToManyField(Waypoint)
class Waypoint(models.Model):
lat = models.FloatField()
lng = models.FloatField()
我想做的是创建一个选择字段,它的值是与当前登录的骑手相关的途经点。
现在我在我的表单中像这样重写了初始化方法:
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()])
但是这样做只是列出了所有的途经点,并没有和任何特定的骑手关联起来。有没有什么好的建议?谢谢。
8 个回答
9
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)])
问题是,当你在更新请求中这样做时,之前的值会丢失!
13
对于你的问题,有一个现成的解决方案:ModelChoiceField。
通常来说,当你需要创建或修改数据库里的对象时,使用 ModelForm
是个不错的选择。它在95%的情况下都能正常工作,而且比自己写代码要简单得多。
204
你可以通过把用户信息传递给表单初始化来过滤路径点。
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)
如果是模型表单的话。
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