Django将自定义表单参数传递给Formset [英] Django Passing Custom Form Parameters to Formset

查看:124
本文介绍了Django将自定义表单参数传递给Formset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


这是在Django 1.9中与 form_kwargs

我有一个Django窗体,如下所示:

I have a Django Form that looks like this:

class ServiceForm(forms.Form):
    option = forms.ModelChoiceField(queryset=ServiceOption.objects.none())
    rate = forms.DecimalField(widget=custom_widgets.SmallField())
    units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField())

    def __init__(self, *args, **kwargs):
        affiliate = kwargs.pop('affiliate')
        super(ServiceForm, self).__init__(*args, **kwargs)
        self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate)

我把这个表单称为这样的:

I call this form with something like this:

form = ServiceForm(affiliate=request.affiliate)

其中 request.affiliate 是登录用户。我的问题是,我现在想将这个单一的表单变成一个表单集。

Where request.affiliate is the logged in user. This works as intended.

我无法想像的是,在创建表单集时,我可以如何将会员信息传递给各个表单。根据文档要做一个表单,我需要这样做:

My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:

ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3)

然后我需要像这样创建它:

And then I need to create it like this:

formset = ServiceFormSet()

现在我如何以这种方式通过affiliate = request.affiliate到个人表单?

Now how can I pass affiliate=request.affiliate to the individual forms this way?

推荐答案

我会使用<一个href =http://docs.python.org/2/library/functools.html#functools.partial =noreferrer> functools.partial 和 functools.wraps

from functools import partial, wraps
from django.forms.formsets import formset_factory

ServiceFormSet = formset_factory(wraps(ServiceForm)(partial(ServiceForm, affiliate=request.affiliate)), extra=3)

I认为这是最干净的方法,并不会以任何方式影响ServiceForm(即通过使其难以进行子类化)。

I think this is the cleanest approach, and doesn't affect ServiceForm in any way (i.e. by making it difficult to subclass).

这篇关于Django将自定义表单参数传递给Formset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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