简体   繁体   English

django admin-根据单选按钮的选择,显示不同的字段

[英]django admin - depending on radio button choice, show different fields

I am trying to do this cool stuff in django admin 我正在尝试在django admin中做这个很酷的东西

I have a model which has a ImageField. 我有一个具有ImageField的模型。 What I want is that the my other coworkers are able to decide if they want to upload image or just paste the image link. 我想要的是其他同事能够决定是否要上传图像或仅粘贴图像链接。

like 喜欢

<radio>: upload           <radio>: link

and depending on choice, respective field (which is model's imageField) will show up for under these radio buttons. 然后根据选择,这些单选按钮下方将显示相应的字段(即模型的imageField)。

how can I achieve this in django admin? 我如何在django admin中实现呢?

You'll need to add the additional field to your admin form class, then add some JavaScript to show or hide the appropriate field on page load, and also add an event handler to show the field to upload or paste in the link. 您需要将其他字段添加到管理表单类中,然后添加一些JavaScript以在页面加载时显示或隐藏适当的字段,还需要添加事件处理程序以显示要上载或粘贴在链接中的字段。

Both fields would need to allow blank=True and then you'd need to add a clean() method to make sure one of the fields is populated and then set the value appropriately. 这两个字段都需要允许blank=True ,然后您需要添加clean()方法以确保填充其中一个字段,然后适当地设置值。 You might be better off using two separate fields. 使用两个单独的字段可能会更好。

You can leverage the Media inner class to easily add the JavaScript to the page without having to alter the change_form.html template for that app. 您可以利用Media内部类轻松地将JavaScript添加到页面,而无需更改该应用程序的change_form.html模板。 Check out: https://docs.djangoproject.com/en/1.7/topics/forms/media/ for examples of how to add custom CSS and JavaScript to forms. 查看: https : //docs.djangoproject.com/zh-CN/1.7/topics/forms/media/,以获取有关如何向表单添加自定义CSS和JavaScript的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM