forms.py 4.89 KB
Newer Older
Kálmán Viktor committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.
17 18
from django.forms import (
    ModelForm, ModelChoiceField, ChoiceField, Form, CharField, RadioSelect,
19
    Textarea, ValidationError
20
)
Kálmán Viktor committed
21
from django.utils.translation import ugettext_lazy as _
22
from django.template.loader import render_to_string
Kálmán Viktor committed
23

24 25
from sizefield.widgets import FileSizeWidget
from sizefield.utils import filesizeformat
Kálmán Viktor committed
26 27 28 29
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

from request.models import (
30
    LeaseType, TemplateAccessType, TemplateAccessAction,
Kálmán Viktor committed
31
)
32
from dashboard.forms import VmResourcesForm
Kálmán Viktor committed
33 34 35 36 37 38 39 40 41 42 43 44


class LeaseTypeForm(ModelForm):
    @property
    def helper(self):
        helper = FormHelper()
        helper.add_input(Submit("submit", _("Save"),
                                css_class="btn btn-success", ))
        return helper

    class Meta:
        model = LeaseType
Kálmán Viktor committed
45
        fields = ["name", "lease", ]
Kálmán Viktor committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60


class TemplateAccessTypeForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(TemplateAccessTypeForm, self).__init__(*args, **kwargs)

    @property
    def helper(self):
        helper = FormHelper()
        helper.add_input(Submit("submit", _("Save"),
                                css_class="btn btn-success", ))
        return helper

    class Meta:
        model = TemplateAccessType
Kálmán Viktor committed
61
        fields = ["name", "templates", ]
Kálmán Viktor committed
62 63


64 65 66 67 68
class InitialFromFileMixin(object):
    def __init__(self, *args, **kwargs):
        request = kwargs.pop("request", None)
        super(InitialFromFileMixin, self).__init__(*args, **kwargs)

69
        self.initial['message'] = render_to_string(
70
            self.initial_template, {}, request
71 72
        )

73
    def clean_message(self):
74 75 76
        def comp(x):
            return "".join(x.strip().splitlines())

77
        message = self.cleaned_data['message']
78
        if comp(message) == comp(self.initial['message']):
79 80
            raise ValidationError(_("Fill in the message."), code="invalid")
        return message.strip()
81

82 83

class TemplateRequestForm(InitialFromFileMixin, Form):
84
    message = CharField(widget=Textarea, label=_("Message"))
Kálmán Viktor committed
85
    template = ModelChoiceField(TemplateAccessType.objects.all(),
86
                                label=_("Template share"))
Kálmán Viktor committed
87 88
    level = ChoiceField(TemplateAccessAction.LEVELS, widget=RadioSelect,
                        initial=TemplateAccessAction.LEVELS.user)
89 90

    initial_template = "request/initials/template.html"
91 92


93
class LeaseRequestForm(Form):
94
    lease = ModelChoiceField(LeaseType.objects.all(), label=_("Lease"))
95
    message = CharField(widget=Textarea(attrs={'placeholder': 'Why do you need this lease?'}), label=_("Message"))
96

Kálmán Viktor committed
97

98
class ResourceRequestForm(InitialFromFileMixin, VmResourcesForm):
99
    message = CharField(widget=Textarea, label=_("Message"))
100 101

    initial_template = "request/initials/resources.html"
102 103 104 105 106 107 108 109 110 111

    def clean(self):
        cleaned_data = super(ResourceRequestForm, self).clean()
        inst = self.instance
        if (cleaned_data['ram_size'] == inst.ram_size and
                cleaned_data['num_cores'] == inst.num_cores and
                int(cleaned_data['priority']) == inst.priority):
            raise ValidationError(
                _("You haven't changed any of the resources."),
                code="invalid")
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136


class ResizeRequestForm(InitialFromFileMixin, Form):
    message = CharField(widget=Textarea, label=_("Message"))
    size = CharField(widget=FileSizeWidget, label=_('Size'),
                     help_text=_('Size to resize the disk in bytes or with'
                                 ' units like MB or GB.'))

    initial_template = "request/initials/resize.html"

    def __init__(self, *args, **kwargs):
        self.disk = kwargs.pop("disk")
        super(ResizeRequestForm, self).__init__(*args, **kwargs)

    def clean_size(self):
        cleaned_data = super(ResizeRequestForm, self).clean()
        disk = self.disk
        size_in_bytes = cleaned_data.get("size")

        if not size_in_bytes.isdigit() and len(size_in_bytes) > 0:
            raise ValidationError(_("Invalid format, you can use GB or MB!"))
        if int(size_in_bytes) < int(disk.size):
            raise ValidationError(_("Disk size must be greater than the actual"
                                    "size (%s).") % filesizeformat(disk.size))
        return size_in_bytes