Django:根据其他字段的值,使字段可编辑 [英] Django: make field editable depending on the value of other field

查看:194
本文介绍了Django:根据其他字段的值,使字段可编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手,我还没有在广泛的文档中找到答案。我要求研究的指针,而不是工作代码。话虽如此,这是我的问题:



在我的一个模型中,一个BooleanField(它以管理形式呈现为一个复选框)。让我们称之为'A'。如果选中A,则编辑其他字段(例如,CharField'B')是有意义的。那么,有没有办法使B只读,甚至是将其内容更改为一个空字符串,如果A被检查,二进制文件?谢谢。



(Django 1.5.2,Python 2.7.5)

解决方案

你将需要几件事情来做这件事情。您可能可以跳过其中一些,具体取决于您是否主要关心UI或数据库中的数据完整性。



由于用户可以(大概)检查/取消选中客户端的字段A,您需要一些Javascript才能启用/禁用Field B的外观。这些文档显示如何在ModelAdmin类中加载自定义JS:

https://docs.djangoproject.com/en/dev/ref/contrib/admin/ #modeladmin-asset-definitions



在您的ModelForm中,您可能需要检查 __ init __ 方法反对 self.instance.field_a 的值,并替换某种 ReadOnlyWidget 为字段B初始显示窗体。这些文档显示如何给您的ModelAdmin一个自定义窗体类:

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form

如果您正在编写一些Javascript来动态地执行此操作,则可以更容易地跳过此步骤,只需在客户端执行。



最后,您可以使用Django模型验证以确保字段B保存为空值,如果选择字段A:

https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects


I'm new to Django, and I haven't found the answer yet in the extensive documentation. I'm asking for pointers to research, not for working code. That being said, here's my problem:

In one of my models theres a BooleanField (it gets rendered in the admin form as a checkBox). Let's call it 'A'. It only makes sense to edit other field (say, CharField 'B') if A is checked.

So, is there a way to make B read only, or even changing its content to an empty string, dinamically, if A is checked? Thank you.

(Django 1.5.2, Python 2.7.5)

解决方案

You're going to need several things to make this work. You may be able to skip some of them depending if you mainly care abut the UI, or the data integrity in the db.

Since the user can (presumably) check/uncheck Field A on the client-side you need some Javascript to enable/disable the appearance of Field B. These docs show how to load custom JS in your ModelAdmin class:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-asset-definitions

In your ModelForm you may want to do some check in the __init__ method against the value of self.instance.field_a and substitute some kind of ReadOnlyWidget for Field B for the initial display of the form. These docs show how to give your ModelAdmin a custom form class:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
If you are writing some Javascript to do that dynamically it make be easier to skip this step and just do it client-side.

Finally you can use Django model validation to ensure that Field B is saved with a null value if Field A is checked:
https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

这篇关于Django:根据其他字段的值,使字段可编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆