Home > front end >  How to render choices in a Django field based on a condition
How to render choices in a Django field based on a condition

Time:11-05

I have a custom user model:

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    is_worker = models.BooleanField(default=False)
    is_customer = models.BooleanField(default=True)

    def __str__(self):
        return f'{self.username} - {self.is_worker}'

And I have this model services :


from django.db import models
from users.models import CustomUser

SERVICE_CHOICES = (
    ('Carpenter', 'Carpenter'),
    ('Driver', 'Driver'),
    ('Ambulanve', 'Ambulanve'),
    ('Spa', 'Spa'),
    ('Barber', 'Barber'),
    ('Cleaning', 'Cleaning'),
    ('Cook', 'Cook'),
)

class Service(models.Model):
    name  = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    service = models.CharField(choices=SERVICE_CHOICES,max_length=100)

    def __str__(self):
        return f'{self.service} - {self.name}'


In services model, I am using CustomUser model for the name. Whereas, I need only those names where is_worker = True. In my code, I am getting all the users irrespective of the status. How can I change it?

CodePudding user response:

You can use ForeignKey.limit_choices_to to set a limit of available choices for a foreignkey field. In your case :

class Service(models.Model):
    name  = models.ForeignKey(CustomUser, on_delete=models.CASCADE, limit_choices_to={'is_worker': True},)
    service = models.CharField(choices=SERVICE_CHOICES,max_length=100)

    def __str__(self):
        return f'{self.service} - {self.name}'

Django doc

CodePudding user response:

something like that:


    class ServiceForm(ModelForm):
    def __init__(
        self,
        *args,
        **kwargs
    ):
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.is_worker:
            self.fields['service'].widget = forms.Select(
                choices=[(k, v)
                         for i in SERVICE_CHOICES if v in ('Barber', 'Spa')]
            )

  • Related