Django - 将参数传递给内联表单集 [英] Django - Passing parameters to inline formset

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

问题描述

我正在使用 inlineformset_factory 为客户端和会话之间的多对多关系创建字段,并具有中介出席模式。

I am using inlineformset_factory to create fields for a many to many relationship between Clients and Sessions, with an intermediary Attendance model.

我的视图文件中有以下内容:

I have the following in my views file:

AttendanceFormset = inlineformset_factory(
    Session,
    Attendance,
    formset=BaseAttendanceFormSet,
    exclude=('user'),
    extra=1,
    max_num=10,
    )

session = Session(user=request.user)
formset = AttendanceFormset(request.POST, instance=session)

而且,因为我需要覆盖其中一个表单域,所以我将以下内容添加到formset基类中:

And, as I needed to override one of the form fields, I added the following to the formset base class:

class BaseAttendanceFormSet(BaseFormSet):

    def add_fields(self, form, index):
        super(BaseAttendanceFormSet, self).add_fields(form, index)
        form.fields['client'] = forms.ModelChoiceField(
                queryset=Client.objects.filter(user=2))

现在,表单正常工作,但我需要传递一个值到表单集,以便我可以过滤基于当前用户显示的客户,而不仅仅是使用id 2。

Now, the form works correctly, but I need to pass a value into the formset so that I can filter the clients displayed based the current user rather than just using the id 2.

任何人都可以帮助?

任何建议赞赏。

谢谢。

编辑

对于任何人阅读,这对我有用:

For anyone reading, this is what worked for me:

def get_field_qs(field, **kwargs):
        if field.name == 'client':
            return forms.ModelChoiceField(queryset=Client.objects.filter(user=request.user))
        return field.formfield(**kwargs)


推荐答案

inlineformset_factory的formfield_callback param而不是提供一个formset?提供一个可调用的,这反过来返回应该在表单中使用的字段。

How about utilizing the inlineformset_factory's formfield_callback param instead of providing a formset ? Provide a callable which in turns returns the field which should be used in the form.

表单字段回调获取为第一个参数的字段,** kwargs为可选参数(例如:小部件。

Form fields callback gets as 1st parameter the field, and **kwargs for optional params (e.g: widget).

例如(使用request.user作为过滤器,如果需要,替换另一个

For example (using request.user for the filter, replace with another if needed:

def my_view(request):
    #some setup code here

    def get_field_qs(field, **kwargs):
        formfield = field.formfield(**kwargs)
        if field.name == 'client':
            formfield.queryset = formfield.queryset.filter(user=request.user)
        return formfield

    AttendanceFormset = inlineformset_factory(
        ...
        formfield_callback=get_field_qs
        ...
    )

    formset = AttendanceFormset(request.POST, instance=session)

为了更好地了解它,请参阅使用 formfield_callback

To better understand it, see the usage of formfield_callback in Django's FormSet code.

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

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