[英]How to populate choice form from db in Django?
I can't figure out how to populate choice form
from db
. 我不知道如何从db
填充choice form
。 I know about ModelChoiceForm
but the problem seems to be slightly different. 我知道ModelChoiceForm
但问题似乎稍有不同。
I want user
to choose which sector does he work in. For example: 'Finance','Electronics' etc. which I would do simple: 我希望user
选择他在哪个部门工作。例如:“金融”,“电子”等,我可以简单地进行以下操作:
SECTOR_CHOICES = (('finance',_('Finance'),
'electronics',_('Electronics')...
))
But the problem is that I want admin
of the web to be able to add new choices, remove choice etc. 但是问题是我希望网络admin
能够添加新选择,删除选择等。
What came to my mind is to create a simple Model
called Sector
: 我想到的是创建一个名为Sector
的简单Model
:
class Sector(models.Model):
name = models.CharField(max_length=40)
and User
would have new attribute sector = models.ModelChoice(Sector)
. 并且User
将具有新的属性sector = models.ModelChoice(Sector)
。
But I'm scared what would happend when admin
changes or removes a sector which is already used, and more, what if he removes it and the sector
attribute is required? 但是我很害怕当admin
更改或删除一个已经使用的扇区时会发生什么,而且,如果他删除它并且需要sector
属性该怎么办?
How to solve this problem? 如何解决这个问题呢?
I would just override the delete_model as custom action and there check if the selected sector object is in use. 我只是将delete_model覆盖为自定义操作,然后检查所选扇区对象是否在使用中。
def delete_model(modeladmin, request, queryset):
for obj in queryset:
if UserModel.objects.filter(sector=obj).exists():
# do not delete, just add some message warning the admin about it
else:
obj.delete()
class UserModelAdmin(admin.ModelAdmin):
actions = [delete_model]
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.