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

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

问题描述

这已在 Django 1.9 中通过 form_kwargs.

This was fixed in Django 1.9 with 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)

我这样称呼这个表格:

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?

推荐答案

我会使用 functools.partialfunctools.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)

我认为这是最干净的方法,并且不会以任何方式影响 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天全站免登陆