将会话数据传递到 ModelAdmin 内的 ModelForm
我试图在实例方法中初始化 MyModelAdmin 类的表单属性,如下所示:
class MyModelAdmin(admin.ModelAdmin):
def queryset(self, request):
MyModelAdmin.form = MyModelForm(request.user)
我的目标是根据当前会话自定义 MyModelForm
的编辑表单。然而,当我尝试这样做时,我不断收到错误(如下所示)。这是将会话数据传递给 ModelForm 的正确位置吗?如果是这样,那么可能是什么导致了这个错误?
TypeError at ...
异常类型:TypeError
异常值:issubclass() arg 1 必须是类
异常位置:/usr/lib/pymodules/python2.6/django/forms/models.py in 新,第 185 行
I'm trying to initialize the form attribute for MyModelAdmin class inside an instance method, as follows:
class MyModelAdmin(admin.ModelAdmin):
def queryset(self, request):
MyModelAdmin.form = MyModelForm(request.user)
My goal is to customize the editing form of MyModelForm
based on the current session. When I try this however, I keep getting an error (shown below). Is this the proper place to pass session data to ModelForm? If so, then what may be causing this error?
TypeError at ...
Exception Type: TypeError
Exception Value: issubclass() arg 1 must be a class
Exception Location: /usr/lib/pymodules/python2.6/django/forms/models.py in new, line 185
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
结合 Izz ad-Din Ruhulessin 的回答 和 Cikić Nenad 的建议,我最终得到了一个非常出色且简洁的解决方案,如下所示:
然后只需为 modeladmin 设置一个自定义表单,例如:
并在自定义 modelform 类访问请求中,例如:
Combining the good ideas in Izz ad-Din Ruhulessin's answer and the suggestion by Cikić Nenad, I ended up with a very awesome AND concise solution below:
Then just set a custom form for the modeladmin like:
And in the custom modelform class access request like:
理论上,您可以重写 ModelAdmin 的
get_form
方法:请注意,这会返回表单类而不是表单实例。
Theoretically, you can override the ModelAdmin's
get_form
method:Note that this returns a form class and not a form instance.
如果像我这样的新手经过这里:
我必须定义:
然后在上一篇文章的末尾
If some newbie, as myself, passes here:
I had to define:
then at the end of the previous post
我使用查询集来过滤记录,也许这个例子可以帮助你:
i use queryset fot filtering records, maybe this example help you:
这是 nemesisfixx 解决方案的生产/线程安全变体:
Here is a production/thread-safe variation from nemesisfixx solution:
现在在 ModelForm 中,我们可以通过
示例访问它:
Now in ModelForm, we can access it by
Example: