forms.py 3.79 KB
Newer Older
1
from django import forms
2
from django.core.exceptions import ValidationError
3 4
from django.utils.translation import ugettext as _

5 6
from stats.models import Branch, Category, CategoryName, Release

7 8 9

class ReleaseField(forms.ModelChoiceField):
    def __init__(self, *args, **kwargs):
10
        kwargs['required'] = False
Claude Paroz's avatar
Claude Paroz committed
11
        super().__init__(*args, **kwargs)
12
        if 'label' in kwargs:
13 14
            self.is_branch = True

15

16 17
class ModuleBranchForm(forms.Form):
    def __init__(self, module, *args, **kwargs):
Claude Paroz's avatar
Claude Paroz committed
18
        super().__init__(*args, **kwargs)
19
        self.module = module
20
        self.branch_fields = []
21
        default_cat_name = None
Claude Paroz's avatar
Claude Paroz committed
22
        for branch in module.get_branches(reverse=True):
23 24 25 26 27 28
            categs = branch.category_set.order_by('name', 'release__name')
            if len(categs):
                for cat in categs:
                    self.fields[str(cat.id)] = ReleaseField(queryset=Release.objects.all(),
                                                            label=branch.name,
                                                            initial=cat.release.pk)
29 30
                    self.fields[str(cat.id)+'_cat'] = forms.ModelChoiceField(
                        queryset=CategoryName.objects.all(),
31
                        required=False,
32 33
                        initial=cat.name
                    )
34
                    self.branch_fields.append((str(cat.id), str(cat.id)+'_cat'))
35
                default_cat_name = cat.name
36 37 38 39
            else:
                # Branch is not linked to any release
                self.fields[branch.name] = ReleaseField(queryset=Release.objects.all(),
                                                        label=branch.name)
40 41
                self.fields[branch.name + '_cat'] = forms.ModelChoiceField(
                    queryset=CategoryName.objects.all(),
42
                    required=False,
43 44
                    initial=default_cat_name
                )
45
                self.branch_fields.append((branch.name, branch.name+'_cat'))
46

47
        self.fields['new_branch'] = forms.CharField(required=False)
48
        self.fields['new_branch_release'] = ReleaseField(queryset=Release.objects.all())
49 50 51 52
        self.fields['new_branch_category'] = forms.ModelChoiceField(
            queryset=CategoryName.objects.all(),
            initial=default_cat_name
        )
53 54

    def get_branches(self):
55 56
        for rel_field, cat_field in self.branch_fields:
            yield (self[rel_field], self[cat_field])
57 58

    def clean(self):
Claude Paroz's avatar
Claude Paroz committed
59
        cleaned_data = super().clean()
60
        for field_name in list(cleaned_data.keys()):
61 62 63 64
            if (field_name.endswith('_cat') and cleaned_data[field_name] is None
                    and cleaned_data[field_name[:-4]] is not None):
                self.add_error(
                    field_name,
65
                    ValidationError(_("You have to provide a category when a version is specified."))
66
                )
67 68 69 70 71 72
        if cleaned_data['new_branch']:
            try:
                branch = Branch.objects.get(module=self.module, name=cleaned_data['new_branch'])
            except Branch.DoesNotExist:
                # The branch will be created later in the view
                return cleaned_data
73 74 75 76 77 78 79 80 81 82 83 84 85
            if not cleaned_data['new_branch_release']:
                self.add_error(
                    'new_branch_release',
                    ValidationError(
                        "There is already an entry for branch %s. Edit that one if "
                        "you want to remove the release link." % branch
                    )
                )
            else:
                rel = Release.objects.get(pk=cleaned_data['new_branch_release'].pk)
                cat = Category(release=rel, branch=branch, name=cleaned_data['new_branch_category'])
                cat.full_clean()
                cleaned_data['new_category'] = cat
86
        return cleaned_data