[英]Django - Passing parameters to inline formset
I am using inlineformset_factory
to create fields for a many to many relationship between Clients and Sessions, with an intermediary Attendance model. 我使用
inlineformset_factory
为客户端和会话之间的多对多关系创建字段,并使用中间出勤模型。
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)
And, as I needed to override one of the form fields, I added the following to the formset base class: 并且,因为我需要覆盖其中一个表单字段,我将以下内容添加到formset基类:
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))
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. 现在,表单正常工作,但我需要将值传递给formset,以便我可以过滤基于当前用户显示的客户端,而不是仅使用id 2。
Can anyone help? 有人可以帮忙吗?
Any advice appreciated. 任何建议表示赞赏
Thanks. 谢谢。
EDIT 编辑
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)
How about utilizing the inlineformset_factory's formfield_callback param instead of providing a formset ? 如何使用inlineformset_factory的formfield_callback参数而不是提供一个formset? Provide a callable which in turns returns the field which should be used in the form.
提供一个可调用的函数,它依次返回应该在表单中使用的字段。
Form fields callback gets as 1st parameter the field, and **kwargs for optional params (eg: widget). 表单字段回调获取作为字段的第一个参数,** kwargs作为可选参数(例如:小部件)。
For example (using request.user for the filter, replace with another if needed: 例如(对于过滤器使用request.user,如果需要,请替换为另一个:
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)
To better understand it, see the usage of formfield_callback in Django's FormSet code . 为了更好地理解它,请参阅Django的FormSet代码中formfield_callback的用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.