Django form regrouping - How can I regroup a field form queryset like I would do in a template?
I have a Django form for a model called AvailabilityRequested
that has a ManyToMany with another model called Event
.
class Event(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
date = models.DateField(blank=True, null=True)
...
class AvailabilityRequested(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
event = models.ManyToManyField(Event, blank=True)
position = models.OneToOneField(JobPosition, blank=True, on_delete=models.CASCADE, related_name='availability_requested', null=True)
class AvailabilityRequestedForm(forms.ModelForm):
class Meta:
model = AvailabilityRequested
fields = ['event']
def __init__(self, *args, **kwargs):
self.project = kwargs.pop('project')
super(AvailabilityRequestedForm, self).__init__(*args, **kwargs)
self.fields['event'].widget = CheckboxSelectMultiple()
self.fields['event'].to_field_name = "event_name" #event.event_name.name
self.fields['event'].queryset = self.project.jobproject_events.order_by('date')
I built the form and it works fine, however I am trying to now render the events in the AvailabilityRequestedForm
in a specific way inside my template and that's where the problem arise.
Specifically, my goal is to basically display the events grouped by date like in the picture attached.
I originally managed to do achieve my goal when I wasn't using forms but just passing to the template a queryset of dates as follow context['dates'] = project.jobproject_events.order_by('date')
and then using the following template logic.
{% regroup dates by date as event_by_date %}
<thead>
<tr>
{% for date in event_by_date %}
<th colspan="{{ date.list | length }}" scope="col" style="border-right: 1px solid black; text-align: center;"> {{ date.grouper }}</th>
{% endfor %}
</tr>
<tr>
{% for date in event_by_date %}
{% for event in date.list %}
<th scope="col" {% if forloop.last %}style="border-right: 1px solid black;"{% endif %}>{{event.event_name.name}}</th>
{% endfor %}
{% endfor %}
</tr>
</thead>
However, when I switched to using django forms, the regroup tag {% regroup availability_request_form.event by date as event_by_date %}
doesn't work anymore.
Here below you can see both implementations in the page and see how the form regroup is failing while the queryset approach works!
Ideas?