N
N
nurzhannogerbek2017-03-10 09:34:23
Django
nurzhannogerbek, 2017-03-10 09:34:23

How to limit selection in CharField?

Hello! I'm trying to solve the following tasks and I can't find information about them in the official Django documentation. In my data model, there is a field with the CharField type, where it is possible to select one of the values ​​​​set in choices. By default, all values ​​that are in choices are displayed in the admin panel. How can I display only some values ​​or make some values ​​unselectable in choices? For example: for a select, make the values ​​''manager' and 'singer' unavailable. I'm also interested in how to achieve the same behavior in a simple form.
admin.py

class MembershipInline(admin.TabularInline):
    model = Membership
    extra = 1


class MembershipAdmin(admin.ModelAdmin):
    form = MembershipAdminForm
    inlines = (MembershipInline,)
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Group, MembershipAdmin)

forms.py
class MembershipAdminForm(forms.ModelForm):
    class Meta:
        model = Membership
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(MembershipAdminForm, self).__init__(*args, **kwargs)
        self.fields['role'].choices = tuple(choice for choice in ROLE_CHOICES if choice[0] not in ['manager', 'singer'])

models.py
class Group(models.Model):
      ***FIELDS***
      members = models.ManyToManyField(User, through='Membership')

ROLE_CHOICES = (
        ('singer', 'Singer'),
        ('musician', 'Musician'),
        ('manager', 'Manager'),
        ('guitarist', 'Guitarist'),
)

class Membership (models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group= models.ForeignKey(Group, on_delete=models.CASCADE)
    role = models.CharField(max_length=20, choices=ROLE_CHOICES,)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question