Пример #1
0
    def test_validate_text_count(self, text_to_validate, expected_clean_text):
        """Tests that validate text count work as expected"""
        max_length_allowed = len(expected_clean_text)
        validate_text_count(max_length_allowed)(text_to_validate)

        # Verify you get a Validation Error if try go below the max.
        with self.assertRaises(ValidationError):
            validate_text_count(max_length_allowed - 1)(text_to_validate)
Пример #2
0
class CustomCourseForm(CourseForm):
    """ Course Form. """
    organization = forms.ModelChoiceField(queryset=Organization.objects.filter(
        organization_extension__organization_id__isnull=False).order_by(
            Lower('key')),
                                          label=_('Organization Name'),
                                          required=True)
    title = forms.CharField(label=_('Course Title'), required=True)
    number = forms.CharField(label=_('Course Number'),
                             required=True,
                             validators=[validate_text_count(max_length=50)])
    short_description = forms.CharField(
        label=_('Short Description'),
        widget=forms.Textarea,
        required=False,
        validators=[validate_text_count(max_length=255)])
    full_description = forms.CharField(
        label=_('Long Description'),
        widget=forms.Textarea,
        required=False,
        validators=[validate_text_count(max_length=2500)])
    prerequisites = forms.CharField(
        label=_('Prerequisites'),
        widget=forms.Textarea,
        required=False,
        validators=[validate_text_count(max_length=200)])

    # users will be loaded through AJAX call based on organization
    team_admin = UserModelChoiceField(
        queryset=User.objects.none(),
        required=True,
        label=_('Organization Course Admin'),
    )

    subjects = Subject.objects.all().order_by('name')
    primary_subject = forms.ModelChoiceField(queryset=subjects,
                                             label=_('Primary'),
                                             required=False)
    secondary_subject = forms.ModelChoiceField(
        queryset=subjects,
        label=_('Additional Subject (optional)'),
        required=False)
    tertiary_subject = forms.ModelChoiceField(
        queryset=subjects,
        label=_('Additional Subject (optional)'),
        required=False)

    level_type = forms.ModelChoiceField(
        queryset=LevelType.objects.all().order_by('-name'),
        label=_('Level'),
        required=False)

    expected_learnings = forms.CharField(
        label=_('What You Will Learn'),
        widget=forms.Textarea,
        required=False,
        validators=[validate_text_count(max_length=2500)])

    learner_testimonial = forms.CharField(
        label=_('Learner Testimonial'),
        widget=forms.Textarea,
        required=False,
        validators=[validate_text_count(max_length=500)])

    faq = forms.CharField(label=_('FAQ'),
                          widget=forms.Textarea,
                          required=False,
                          validators=[validate_text_count(max_length=2500)])

    syllabus = forms.CharField(
        label=_('Syllabus'),
        widget=forms.Textarea,
        required=False,
        validators=[validate_text_count(max_length=2500)])

    add_new_run = forms.BooleanField(required=False)

    class Meta(CourseForm.Meta):
        model = Course
        widgets = {'image': ClearableImageInput(attrs={'accept': 'image/*'})}
        fields = (
            'title',
            'number',
            'short_description',
            'full_description',
            'expected_learnings',
            'primary_subject',
            'secondary_subject',
            'tertiary_subject',
            'prerequisites',
            'image',
            'team_admin',
            'level_type',
            'organization',
            'is_seo_review',
            'syllabus',
            'learner_testimonial',
            'faq',
            'video_link',
        )

    def __init__(self, *args, **kwargs):
        # In case of edit mode pre-populate the drop-downs
        user = kwargs.pop('user', None)
        organization = kwargs.pop('organization', None)
        if organization:
            org_extension = OrganizationExtension.objects.get(
                organization=organization)
            self.declared_fields['team_admin'].queryset = User.objects.filter(
                groups__name=org_extension.group).order_by(
                    'full_name', 'username')

        if user:
            self.declared_fields[
                'organization'].queryset = get_user_organizations(user)
            self.declared_fields['team_admin'].widget.attrs = {
                'data-user': user.id
            }

        super(CustomCourseForm, self).__init__(*args, **kwargs)

        if user and not is_internal_user(user):
            self.fields['video_link'].widget = forms.HiddenInput()

    def clean_title(self):
        """
        Convert all named and numeric character references in the string
        to the corresponding unicode characters
        """
        return html.unescape(self.cleaned_data.get("title"))

    def clean(self):
        cleaned_data = self.cleaned_data
        organization = cleaned_data.get("organization")
        title = cleaned_data.get("title")
        number = cleaned_data.get("number")
        instance = getattr(self, 'instance', None)
        if not instance.pk:
            if Course.objects.filter(title=title,
                                     organizations__in=[organization
                                                        ]).exists():
                raise ValidationError(
                    {'title': _('This course title already exists')})
            if Course.objects.filter(number=number,
                                     organizations__in=[organization
                                                        ]).exists():
                raise ValidationError(
                    {'number': _('This course number already exists')})
        return cleaned_data