Django 管理员根据请求更改 to_python 输出
我想知道如何根据请求中的数据更改表单字段的行为...特别是因为它与 Django 管理员相关。例如,我想根据请求数据(例如 POST 或会话变量)解密管理中的字段。
我的想法是开始考虑重写 django/contrib/admin/options.py 中的change_view方法,因为它可以访问请求。但是,我不确定如何影响字段值根据请求中的某些值显示字段的方式。如果请求的值正确,则显示该字段值;否则,字段值将返回类似“NA”的内容。
我的想法是,如果我能以某种方式将该请求值放入 to_python() 方法中,我可以直接影响该字段的显示方式。我是否应该尝试将请求值传递到表单 init 中,然后以某种方式传递到字段 init 中?有什么建议我可以如何处理这个问题吗?
感谢您的阅读。
在 models.py 中
class MyModel(models.Model):
hidden_data = models.CharField()
在 admin.py 中
class MyModelAdmin(models.ModelAdmin):
class Meta:
model = MyModel
def change_view(self, request, object_id, extra_context=None):
.... # Perhaps this is where I'd do a lot of overriding?
....
return self.render_change_form(request, context, change=True, obj=obj)
I'm wondering how to change the behavior of a form field based on data in the request... especially as it relates to the Django Admin. For example, I'd like to decrypt a field in the admin based on request data (such as POST or session variables).
My thoughts are to start looking at overriding the change_view method in django/contrib/admin/options.py, since that has access to the request. However, I'm not sure how to affect how the field value displays the field depending on some value in the request. If the request has the correct value, the field value would be displayed; otherwise, the field value would return something like "NA".
My thought is that if I could somehow get that request value into the to_python() method, I could directly impact how the field is displayed. Should I try passing the request value into the form init and then somehow into the field init? Any suggestions how I might approach this?
Thanks for reading.
In models.py
class MyModel(models.Model):
hidden_data = models.CharField()
In admin.py
class MyModelAdmin(models.ModelAdmin):
class Meta:
model = MyModel
def change_view(self, request, object_id, extra_context=None):
.... # Perhaps this is where I'd do a lot of overriding?
....
return self.render_change_form(request, context, change=True, obj=obj)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我还没有对此进行测试,但您可以覆盖
ModelAdmin
的render_change_form
方法,潜入代码中以更改change_view< 之间的字段值/code> 被处理并渲染实际的模板
I haven't tested this, but you could just overwrite the
render_change_form
method of theModelAdmin
to sneak in your code to change the field value between when thechange_view
is processed and the actual template rendered