unknown
unknown

Reputation: 321

How to form data for select?

There is a model Provider. It has the field role, which has two options: Individual and Organization. There are summary field and organization field.

It is necessary that in the form (in the template), in the select, the data is displayed in the following way: if the record is associated with Individual, then summqry + user, and if with the Organization, then the Organization title.

models.py

ROLE_INDIVIDUAL = 'individual'
ROLE_ORGANIZATION = 'organization'

ROLE_CHOICES = (
    (ROLE_INDIVIDUAL, _('Individual')),
    (ROLE_ORGANIZATION, _('Organization'))
    )

class Provider(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    role = models.CharField(max_length=255, choices=ROLE_CHOICES, default=ROLE_INDIVIDUAL)
    summary = models.CharField(max_length=255, default='')
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)

forms.py

class ProductCreateForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = (..., 'on_behalf', ...)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('initial').get('request')
        super(ProductCreateForm, self).__init__(*args, **kwargs)
        self.fields['on_behalf'] = ModelChoiceField(queryset=Provider.objects.filter(user=user.id))

Upvotes: 0

Views: 27

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

You should define the __str__ method on Provider to return the string you want.

class Provider(models.Model):
    ...
    def __str__(self):
        if self.role == ROLE_INDIVIDUAL:
            return '{} + {}'.format(self.summary, self.user)
        else:
            return self.organization.title

Upvotes: 1

Related Questions