根据值在 Admin 中自定义 Django 表单字段
如何根据表单字段的值在 Django 管理中自定义表单的显示?例如,我有一个默认值为“0”的字段。如果该字段已设置为非零值,我想在表单上显示一个附加的“编辑”链接,该链接将链接到一个单独的页面,允许编辑与相关模型相关的其他字段。我已经找到了如何自定义管理员的表单模板,但我找不到如何访问表单字段的实际值以便在模板中添加 if/else 语句。
我尝试挖掘源代码,并将我的字段实例跟踪到 django.contrib.admin.AdminField.field->django.forms.BoundField 但显示 BoundField 的字段和数据属性不显示存储在默认表单字段小部件标记中的值。如何访问模板内特定字段的数据值,以便我可以执行如下操作?
{% for fieldset in inline_admin_form %}
{% for line in fieldset %}
{% for field in line %}
{{field.field}} {% if field.field.value != 0 %}<a href="/some/path/to/model/{{field.value}}">Edit</a>{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
How do you customize the display of a form in Django's admin based on a form field's value? For example, I have a field whose default value is "0". If the field has been set to a non-zero value, I want to show an additional "Edit" link on the form, which would link to a separate page allowing edit other fields related to a related model. I've found how to customize admin's form template, but I can't find how to access a form field's actual value in order to add the if/else statement in the template.
I've tried digging through the source code, and I've traced my field instance to django.contrib.admin.AdminField.field->django.forms.BoundField
but displaying the BoundField's field and data attribute doesn't show the value stored in the default form field widget markup. How do I access a specific field's data value inside a template so I can do something like the following?
{% for fieldset in inline_admin_form %}
{% for line in fieldset %}
{% for field in line %}
{{field.field}} {% if field.field.value != 0 %}<a href="/some/path/to/model/{{field.value}}">Edit</a>{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
刚刚在 shell 会话中输入随机变量 (ipython ftw) 并发现了这个:
试一试!
Just did a shell session typing in random variables (ipython ftw) and found this:
Give it a shot!