From bb2d8acdcc511aa33db185698bc9ad755f33d014 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Aleksander=20=C5=81ukasz?= Date: Thu, 29 Aug 2013 16:55:30 +0200 Subject: [PATCH] Forum: Grouping lessons by their section on the forum post form --- forum/forms.py | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/forum/forms.py b/forum/forms.py index ec8a3be..9e931db 100644 --- a/forum/forms.py +++ b/forum/forms.py @@ -1,10 +1,39 @@ from django import forms +from django.forms.models import ModelChoiceIterator from django.utils.translation import ugettext as _ import pybb.forms from catalogue.models import Lesson +class GroupedModelChoiceIterator(ModelChoiceIterator): + def __init__(self, field): + super(GroupedModelChoiceIterator, self).__init__(field) + self.queryset = self.field.grouping_model.objects + self.items_queryset = self.field.queryset + + def choice(self, obj): + items_query = self.items_queryset.filter(**{self.field.grouping_fk_field: obj}) + items = [super(GroupedModelChoiceIterator, self).choice(item) for item in items_query.all()] + return (unicode(obj), items) + + +class GroupedModelChoiceField(forms.ModelChoiceField): + + def __init__(self, queryset, grouping_fk_field, **kwargs): + self.grouping_fk_field = grouping_fk_field + self.grouping_model = queryset.model._meta.get_field(grouping_fk_field).rel.to + super(GroupedModelChoiceField, self).__init__(queryset, **kwargs) + + def _get_choices(self): + toret = super(GroupedModelChoiceField, self)._get_choices() + if isinstance(toret, ModelChoiceIterator): + toret = GroupedModelChoiceIterator(self) + return toret + + choices = property(_get_choices, forms.ModelChoiceField.choices.fset) + + class PostForm(pybb.forms.PostForm): - lesson = forms.ModelChoiceField(label = _('Related lesson'), queryset = Lesson.objects.all(), required = False) - \ No newline at end of file + lesson = GroupedModelChoiceField(label = _('Related lesson'), queryset = Lesson.objects.all(), + grouping_fk_field = 'section', required = False) -- 2.20.1