forms.py 3.92 KB
Newer Older
Sarina Canelake committed
1 2 3
"""
Defines a form for providing validation of CourseEmail templates.
"""
4 5 6 7
import logging

from django import forms
from django.core.exceptions import ValidationError
8
from opaque_keys import InvalidKeyError
9 10
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locations import SlashSeparatedCourseKey
11

12 13 14
from bulk_email.models import COURSE_EMAIL_MESSAGE_BODY_TAG, CourseAuthorization, CourseEmailTemplate
from xmodule.modulestore.django import modulestore

15 16 17
log = logging.getLogger(__name__)


18
class CourseEmailTemplateForm(forms.ModelForm):
19 20
    """Form providing validation of CourseEmail templates."""

21
    name = forms.CharField(required=False)
22

23
    class Meta(object):
24
        model = CourseEmailTemplate
25
        fields = ('html_template', 'plain_template', 'name')
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

    def _validate_template(self, template):
        """Check the template for required tags."""
        index = template.find(COURSE_EMAIL_MESSAGE_BODY_TAG)
        if index < 0:
            msg = 'Missing tag: "{}"'.format(COURSE_EMAIL_MESSAGE_BODY_TAG)
            log.warning(msg)
            raise ValidationError(msg)
        if template.find(COURSE_EMAIL_MESSAGE_BODY_TAG, index + 1) >= 0:
            msg = 'Multiple instances of tag: "{}"'.format(COURSE_EMAIL_MESSAGE_BODY_TAG)
            log.warning(msg)
            raise ValidationError(msg)
        # TODO: add more validation here, including the set of known tags
        # for which values will be supplied.  (Email will fail if the template
        # uses tags for which values are not supplied.)

    def clean_html_template(self):
        """Validate the HTML template."""
        template = self.cleaned_data["html_template"]
        self._validate_template(template)
        return template

    def clean_plain_template(self):
        """Validate the plaintext template."""
        template = self.cleaned_data["plain_template"]
        self._validate_template(template)
        return template
53

54 55
    def clean_name(self):
        """Validate the name field. Enforce uniqueness constraint on 'name' field"""
56 57 58 59 60

        # Note that we get back a blank string in the Form for an empty 'name' field
        # we want those to be set to None in Python and NULL in the database
        name = self.cleaned_data.get("name").strip() or None

61 62 63 64 65 66 67 68 69 70 71 72
        # if we are creating a new CourseEmailTemplate, then we need to
        # enforce the uniquess constraint as part of the Form validation
        if not self.instance.pk:
            try:
                CourseEmailTemplate.get_template(name)
                # already exists, this is no good
                raise ValidationError('Name of "{}" already exists, this must be unique.'.format(name))
            except CourseEmailTemplate.DoesNotExist:
                # this is actually the successful validation
                pass
        return name

73

74
class CourseAuthorizationAdminForm(forms.ModelForm):
75 76
    """Input form for email enabling, allowing us to verify data."""

77
    class Meta(object):
78
        model = CourseAuthorization
79
        fields = '__all__'
80 81 82

    def clean_course_id(self):
        """Validate the course id"""
83
        cleaned_id = self.cleaned_data["course_id"]
84
        try:
85
            course_key = CourseKey.from_string(cleaned_id)
86
        except InvalidKeyError:
87 88 89
            try:
                course_key = SlashSeparatedCourseKey.from_deprecated_string(cleaned_id)
            except InvalidKeyError:
90
                msg = u'Course id invalid.'
91 92 93 94 95
                msg += u' --- Entered course id was: "{0}". '.format(cleaned_id)
                msg += 'Please recheck that you have supplied a valid course id.'
                raise forms.ValidationError(msg)

        if not modulestore().has_course(course_key):
96
            msg = u'COURSE NOT FOUND'
97
            msg += u' --- Entered course id was: "{0}". '.format(course_key.to_deprecated_string())
98
            msg += 'Please recheck that you have supplied a valid course id.'
99 100
            raise forms.ValidationError(msg)

101
        return course_key