Rendering with CheckboxSelectMultiple

The following model is being used for generating a selection list:

class Event(models.Model):
date = models.DateField()
description = models.CharField()

The following form is being used to render a list of Events:

    events = forms.ModelMultipleChoiceField(
        queryset=Event.objects.all(),
        widget=forms.CheckboxSelectMultiple,
    )

The rendered result is:

All Events
Events:

 Event object (1)
 Event object (2)
 Event object (3)

I would like the result to look like this:

All Events

 Event (1): Date <date>, Description <description>
 Event (2): Date <date>, Description <description>

I have searched for the answer few hours with no avail. Would appreciate some guidance.

See the docs below ModelChoiceField.iterator (Not the docs for iterator itself, but the paragraph below it.)

Briefly, the __str__ method on a class is used to generate the entries for the select list. You’re seeing the output of the default __str__ method for your class.
You can either provide your own __str__ method for that model, or you can subclass the ModelMultipleChoiceField as described in those docs. (You may need to do this if you have other representations for that model where you need to customize the __str__ method.)

2 Likes

Thank you so much. It worked.

1 Like

Could you please post the improved code too. So others can learn :wink:

Here is the revised model class:

class Event(models.Model):
    class Specialties(models.TextChoices):
        ORTHO = "Orthopedics"
        FAMILY = "Family"

    date = models.DateField()
    specialty = models.CharField(
        max_length=11,
        choices=Specialties.choices,
        default=Specialties.FAMILY,
    )
    description = models.CharField(max_length=100)

    class Meta:
        app_label = "events"

    def __str__(self):
        return (
            f"ID: {self.id}, Date {self.date}, Speciality {self.specialty}, "
            f"Description {self.description}"
        )
1 Like

Thank you. That helps :blush: