在 django admin 中使用change_view向 ModelForm 构造函数添加额外的参数
我希望能够在 django admins clean()
方法中访问请求对象。我如何自定义此 让用户从管理验证类使用 django admins modelform
我需要进行什么样的修改到下面的 change_view
,
def change_view(self, request, object_id, extra_context=None):
self.form = GroupForm
result = super(GroupsAdmin, self).change_view(request, object_id, extra_context)
return result
以便它调用下面具有 request
参数的构造函数
class GroupForm(forms.ModelForm):
class Meta:
model = Group
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(GroupForm, self).__init__(*args, **kwargs)
I would like to be able to access request object in django admins clean()
method. How can I customize this getting the user from a admin validation class to work with django admins modelform
What kind of modification do i need to make to change_view
below
def change_view(self, request, object_id, extra_context=None):
self.form = GroupForm
result = super(GroupsAdmin, self).change_view(request, object_id, extra_context)
return result
so that it calls the constructor below which has the request
argument
class GroupForm(forms.ModelForm):
class Meta:
model = Group
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(GroupForm, self).__init__(*args, **kwargs)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
鉴于没有为此提供答案,我想我应该强调我是如何解决这个问题的,以防其他人可能会发现该信息有用。
我最终通过定义自定义中间件并使用 ThreadLocals 解决了这个问题。
首先在
forms.py
中定义一个 ThreadLocals 类,如下所示然后在
settings.py
中确保启用中间件最后访问请求对象就像这样简单
Seeing as no answer was ever provided for this, I figured I should highlight how I resolved this just in case someone else might find the info useful.
I eventually solved this on defining a custom middleware and using
ThreadLocals
.First define a ThreadLocals class in your
forms.py
as shown belowThen in your
settings.py
make sure to enable the middlewareAnd finally accessing the request object is as easy as