Django - 将参数传递给内联表单集
我正在使用 inlineformset_factory 为客户端和会话之间的多对多关系创建字段,并使用中介考勤模型。
我的视图文件中有以下内容:
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)
而且,由于我需要覆盖其中一个表单字段,因此我将以下内容添加到表单集基类中:
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。
有人可以帮忙吗?
任何建议表示赞赏。
谢谢。
编辑
对于任何阅读的人来说,这对我有用:
def get_field_qs(field, **kwargs):
if field.name == 'client':
return forms.ModelChoiceField(queryset=Client.objects.filter(user=request.user))
return field.formfield(**kwargs)
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)
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))
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.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如何利用 inlineformset_factory 的 formfield_callback 参数而不是提供 formset ?提供一个可调用对象,该可调用对象依次返回应在表单中使用的字段。
表单字段回调获取字段作为第一个参数,**kwargs 获取可选参数(例如:小部件)。
例如(使用 request.user 作为过滤器,如果需要则替换为另一个:
为了更好地理解它,请参阅 Django 的 FormSet 代码中的 formfield_callback。
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.
Form fields callback gets as 1st parameter the field, and **kwargs for optional params (e.g: widget).
For example (using request.user for the filter, replace with another if needed:
To better understand it, see the usage of formfield_callback in Django's FormSet code.