创建动态选择字段

时间:2010-08-05 23:39:55

标签: python django django-forms django-templates

我在尝试了解如何在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()])

但所有这一切都是列出所有航点,它们与任何特定的骑手没有联系。有任何想法吗?感谢。

8 个答案:

答案 0 :(得分:175)

您可以通过将用户传递给表单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)]
        )
启动表单时,从您的视图中

传递用户

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

答案 1 :(得分:11)

针对您的问题提供了内置解决方案:ModelChoiceField

通常,当您需要创建/更改数据库对象时,始终值得尝试使用ModelForm。在95%的情况下工作,它比创建自己的实现更清晰。

答案 2 :(得分: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)])

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

答案 3 :(得分:4)

如何在初始化时将rider实例传递给表单?

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) 

答案 4 :(得分:2)

具有正常选择字段的工作解决方案下方。 我的问题是每个用户都有自己的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

答案 5 :(得分: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)

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

答案 6 :(得分:1)

您可以将该字段声明为表单的一流属性,并且可以动态设置选项:

class WaypointForm(forms.Form):
    waypoints = forms.ChoiceField(choices=[])

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

您还可以使用ModelChoiceField并以类似方式在init上设置查询集。

答案 7 :(得分:0)

如果您需要django admin中的动态选择字段;这适用于Django> = 2.1。

class CarAdminForm(forms.ModelForm):
    class Meta:
        model = Car

    def __init__(self, *args, **kwargs):
        super(CarForm, self).__init__(*args, **kwargs)

        # Now you can make it dynamic.
        choices = (
            ('audi', 'Audi'),
            ('tesla', 'Tesla')
        )

        self.fields.get('car_field').choices = choices

    car_field = forms.ChoiceField(choices=[])

@admin.register(Car)
class CarAdmin(admin.ModelAdmin):
    form = CarAdminForm

希望这会有所帮助。