forms.py 4.99 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 23
from django.template import RequestContext
from django.template.loader import render_to_string
Kálmán Viktor committed
24

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

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


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
46
        fields = ["name", "lease", ]
Kálmán Viktor committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61


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
62
        fields = ["name", "templates", ]
Kálmán Viktor committed
63 64


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

70
        self.initial['message'] = render_to_string(
71
            self.initial_template,
72
            RequestContext(request, {}).flatten(),
73 74
        )

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

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

84 85

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

    initial_template = "request/initials/template.html"
93 94


95 96
class LeaseRequestForm(InitialFromFileMixin, Form):
    lease = ModelChoiceField(LeaseType.objects.all(), label=_("Lease"))
97
    message = CharField(widget=Textarea, label=_("Message"))
98

99 100
    initial_template = "request/initials/lease.html"

Kálmán Viktor committed
101

102
class ResourceRequestForm(InitialFromFileMixin, VmResourcesForm):
103
    message = CharField(widget=Textarea, label=_("Message"))
104 105

    initial_template = "request/initials/resources.html"
106 107 108 109 110 111 112 113 114 115

    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")
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140


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