32e91e088721233a02fe88dd506eb1d6c3923339
[edumed.git] / curriculum / views.py
1 from django.db import models
2 from django.views.generic import DetailView, ListView
3 from django.utils.datastructures import SortedDict
4 from .models import Competence, Section, Level, CompetenceLevel
5
6
7 class CompetenceDetailView(DetailView):
8     model = Competence
9
10
11 class CompetencesView(ListView):
12     model = Competence
13
14     def get_context_data(self, **kwargs):
15         context = super(CompetencesView, self).get_context_data(**kwargs)
16         context['levels'] = Level.objects.all()
17         context['sections'] = Section.objects.all()
18
19         errors = {}
20
21         try:
22             level = Level.objects.get(slug=self.request.GET.get('level'))
23         except Level.DoesNotExist:
24             level = None
25         context['level'] = level
26
27         comp_ids = set()
28         for c in self.request.GET.getlist('c'):
29             try:
30                 comp_ids.add(int(c))
31             except ValueError:
32                 pass
33         context['comp_ids'] = comp_ids
34         sect_ids = set()
35         for c in self.request.GET.getlist('s'):
36             try:
37                 sect_ids.add(int(c))
38             except ValueError:
39                 pass
40         context['sect_ids'] = sect_ids
41
42         if not (comp_ids or sect_ids):
43             if level:
44                 errors["competences"] = "Please!"
45         elif level is None:
46             errors["level"] = "Please!"
47         else:
48             chosen_competences = SortedDict()
49             for competence in Competence.objects.filter(
50                     models.Q(pk__in=comp_ids) | models.Q(section__pk__in=sect_ids)):
51                 try:
52                     competence.for_level_ = competence.for_level(level)
53                 except CompetenceLevel.DoesNotExist:
54                     pass
55                 chosen_competences.setdefault(competence.section, []).append(competence)
56             context['chosen_competences'] = chosen_competences
57
58         context["errors"] = errors
59         return context