自定义 Django 表单小部件? - 姜戈
我这里遇到一个小问题!
我发现以下方法是全球公认的自定义 Django 管理字段的方法。
from django import forms
from django.utils.safestring import mark_safe
class AdminImageWidget(forms.FileInput):
"""
A ImageField Widget for admin that shows a thumbnail.
"""
def __init__(self, attrs={}):
super(AdminImageWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
output = []
if value and hasattr(value, "url"):
output.append(('<a target="_blank" href="%s">'
'<img src="%s" style="height: 28px;" /></a> '
% (value.url, value.url)))
output.append(super(AdminImageWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
我需要访问模型的其他字段才能决定如何显示该字段!
例如:
如果我要跟踪一个值,我们将其称为“销售”。
如果我希望根据其他字段自定义销售额的显示方式,我们将其称为“转化率”。
在覆盖销售小部件时,我没有明显的方法来访问转化率字段!
任何解决此问题的想法将不胜感激!谢谢 :)
I'm having a little problem here!
I have discovered the following as being the globally accepted method for customizing Django admin field.
from django import forms
from django.utils.safestring import mark_safe
class AdminImageWidget(forms.FileInput):
"""
A ImageField Widget for admin that shows a thumbnail.
"""
def __init__(self, attrs={}):
super(AdminImageWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
output = []
if value and hasattr(value, "url"):
output.append(('<a target="_blank" href="%s">'
'<img src="%s" style="height: 28px;" /></a> '
% (value.url, value.url)))
output.append(super(AdminImageWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
I need to have access to other field of the model in order to decide how to display the field!
For example:
If I am keeping track of a value, let us call it "sales".
If I wish to customize how sales is displayed depending on another field, let us call it "conversion rate".
I have no obvious way of accessing the conversion rate field when overriding the sales widget!
Any ideas to work around this would be highly appreciated! Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是对的,小部件本身是独立的。我对于做一些更复杂的事情的第一个想法是提供一个自定义管理模板来执行您想要的操作,或者传递一段 JavaScript 代码来处理相互关联的字段(很像预填充字段的工作方式)。
You are correct that the widgets themselves are independent. My first thought for doing something more complex is to either provide a custom admin template that does what you want, or to pass in a piece of javascript code to handle the interrelated fields (much like how prepopulated fields work).
您可能想使用 管理员的自定义表单
you probably want to use a custom form for the admin