Reputation: 18705
I can't figure out how to populate choice form
from db
. I know about ModelChoiceForm
but the problem seems to be slightly different.
I want user
to choose which sector does he work in. For example: 'Finance','Electronics' etc. which I would do simple:
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.
What came to my mind is to create a simple Model
called Sector
:
class Sector(models.Model):
name = models.CharField(max_length=40)
and User
would have new attribute 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?
How to solve this problem?
Upvotes: 0
Views: 44
Reputation: 37846
I would just override the delete_model as custom action and there check if the selected sector object is in use.
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]
# ...
Upvotes: 1