从我的通用视图或URL将变量设置为forms.py的queryset [英] set variable into queryset of forms.py from my generic view or url

查看:63
本文介绍了从我的通用视图或URL将变量设置为forms.py的queryset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 forms.py queryset 中设置一个动态变量,我使用了 __ init __ 传递动态变量,我认为forms.py中的代码是正确的,问题是如何在视图中传递变量?

I want to set a dynamic variable into queryset of forms.py , I used __init__ to pass the dynamic variable , I think the code in forms.py is correct, the problem is how to pass the variable in views?

forms.py

class ContainerForm(forms.ModelForm):
    vehicle=forms.ModelChoiceField(required=False,queryset=Vehicle.objects.all(),widget=forms.Select(attrs={'class':'form-control'}))

  def __init__(self, *args, **kwargs):
      vehicle_id = kwargs.pop('vehicle_id',None)
      super(ContainerForm, self).__init__(*args, **kwargs)
      if vehicle_id:
          self.fields['vehicle'].queryset = Vehicle.objects.filter(id=vehicle_id)

views.py

class ContainerCreate(CreateView):
    form_class = ContainerForm(id= vehicle_id)
    template_name = 'vehicule_app/container_form.html'

错误说:

Exception Value:'ContainerForm' object is not callable


推荐答案

如果要从URL使用 vehicle_id ,则可以从模型形式中排除该字段:

If you want to use the vehicle_id from the URL, then you can exclude the field from the model form:

class ContainerForm(forms.ModelForm):
    class Meta:
        model = Container
        exclude = ['vehicle'] 

然后可以从 self.kwargs ,并在 get_form_kwargs 中设置表单实例的值:

You can then fetch the parameter from self.kwargs, and set the value on the form's instance in get_form_kwargs:

class ContainerCreate(CreateView):
    form_class = ContainerForm
    template_name = 'vehicule_app/container_form.html'

    def get_form_kwargs(self):
        kwargs = super(ContainerCreate, self).get_form_kwargs()
        if kwargs['instance'] is None:
            kwargs['instance'] = Container()
            kwargs['instance'].vehicle_id = self.kwargs['pk']  # Fetch the vehicle_id from the URL
        return kwargs

请注意,上面的代码不会验证URL中的ID。用户可以将其更改为自己喜欢的任何值。

Note that the above code will not validate the id from the URL. The user could change it to any value they like.

如果要在表单中保留 vehicle 字段但只有一个选择,然后覆盖 __ init __ 方法并设置查询集。

If you want to keep the vehicle field in the form but with a single choice, then override the __init__ method and set the queryset.

class ContainerForm(forms.ModelForm):
    class Meta:
        model = Container

    def __init__(self, *args, **kwargs):
        vehicle_id = kwargs.pop('vehicle_id')
        self.fields['vehicle'].queryset = Vehicle.objects.filter(id=vehicle_id)

然后在 get_form_kwargs 方法中,将 vehicle_id 添加到kwargs而是:

Then in the get_form_kwargs method, add vehicle_id to kwargs instead:

class ContainerCreate(CreateView):
    form_class = ContainerForm
    template_name = 'vehicule_app/container_form.html'

    def get_form_kwargs(self):
        kwargs = super(ContainerCreate, self).get_form_kwargs()
        kwargs['vehicle_id'] = self.kwargs['pk']
        return kwargs

这篇关于从我的通用视图或URL将变量设置为forms.py的queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆