English version wip - urls, navigation
[edumed.git] / forum / forms.py
1 from django import forms
2 from django.forms.models import ModelChoiceIterator
3 from django.utils.translation import ugettext as _
4 import pybb.forms
5
6 from catalogue.models import Lesson
7
8
9 class GroupedModelChoiceIterator(ModelChoiceIterator):
10     def __init__(self, field):
11         super(GroupedModelChoiceIterator, self).__init__(field)
12         self.queryset = self.field.grouping_model.objects
13         self.items_queryset = self.field.queryset
14     
15     def choice(self, obj):
16         items_query = self.items_queryset.filter(**{self.field.grouping_fk_field: obj})
17         items = [super(GroupedModelChoiceIterator, self).choice(item) for item in items_query.all()]
18         return (unicode(obj), items)
19
20
21 class GroupedModelChoiceField(forms.ModelChoiceField):
22     
23     def __init__(self, queryset, grouping_fk_field, **kwargs):
24         self.grouping_fk_field = grouping_fk_field
25         self.grouping_model = queryset.model._meta.get_field(grouping_fk_field).rel.to
26         super(GroupedModelChoiceField, self).__init__(queryset, **kwargs)
27
28     def _get_choices(self):
29         toret = super(GroupedModelChoiceField, self)._get_choices()
30         if isinstance(toret, ModelChoiceIterator):
31             toret = GroupedModelChoiceIterator(self)
32         return toret
33
34     choices = property(_get_choices, forms.ModelChoiceField.choices.fset)
35
36
37 class PostForm(pybb.forms.PostForm):
38     lesson = GroupedModelChoiceField(label = _('Related lesson'), queryset = Lesson.objects.all(),
39         grouping_fk_field = 'section', required = False)