简体   繁体   中英

How to populate choice form from db in Django?

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?

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]
    # ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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