Skip to content
This repository has been archived by the owner on Feb 13, 2022. It is now read-only.

Commit

Permalink
Merge branch 'release/6.9.2'
Browse files Browse the repository at this point in the history
  • Loading branch information
moh-moola committed Jul 24, 2018
2 parents 1c5d68f + 58aecd9 commit e4c5c60
Show file tree
Hide file tree
Showing 3 changed files with 114 additions and 4 deletions.
71 changes: 70 additions & 1 deletion molo/surveys/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
from .widgets import NaturalDateInput


CHARACTER_COUNT_CHOICE_LIMIT = 512


class CharacterCountWidget(forms.TextInput):
class Media:
js = ('js/widgets/character_count.js',)
Expand All @@ -31,6 +34,50 @@ def render(self, name, value, attrs=None):
)


class CharacterCountMixin(object):
max_length = CHARACTER_COUNT_CHOICE_LIMIT

def __init__(self, *args, **kwargs):
self.max_length = kwargs.pop('max_length', self.max_length)
super(CharacterCountMixin, self).__init__(*args, **kwargs)

self.error_messages['max_length'] = _(
'This field can not be more than {max_length} characters long'
).format(max_length=self.max_length)

def validate(self, value):
super(CharacterCountMixin, self).validate(value)
if len(value) > self.max_length:
raise ValidationError(
self.error_messages['max_length'],
code='max_length', params={'value': value},
)


class CharacterCountMultipleChoiceField(
CharacterCountMixin, forms.MultipleChoiceField
):
""" Limit character count for Multi choice fields """


class CharacterCountChoiceField(
CharacterCountMixin, forms.ChoiceField
):
""" Limit character count for choice fields """


class CharacterCountCheckboxSelectMultiple(
CharacterCountMixin, forms.CheckboxSelectMultiple
):
""" Limit character count for checkbox fields """


class CharacterCountCheckboxInput(
CharacterCountMixin, forms.CheckboxInput
):
""" Limit character count for checkbox fields """


class MultiLineWidget(forms.Textarea):
def render(self, name, value, attrs=None):
return format_html(
Expand Down Expand Up @@ -63,6 +110,28 @@ def create_datetime_field(self, field, options):
def create_positive_number_field(self, field, options):
return forms.DecimalField(min_value=0, **options)

def create_dropdown_field(self, field, options):
options['choices'] = map(
lambda x: (x.strip(), x.strip()),
field.choices.split(','))
return CharacterCountChoiceField(**options)

def create_radio_field(self, field, options):
options['choices'] = map(
lambda x: (x.strip(), x.strip()),
field.choices.split(','))
return CharacterCountChoiceField(widget=forms.RadioSelect, **options)

def create_checkboxes_field(self, field, options):
options['choices'] = [
(x.strip(), x.strip()) for x in field.choices.split(',')
]
options['initial'] = [
x.strip() for x in field.default_value.split(',')
]
return CharacterCountMultipleChoiceField(
widget=forms.CheckboxSelectMultiple, **options)

@property
def formfields(self):
'''
Expand All @@ -76,7 +145,6 @@ def formfields(self):

for field in self.fields:
options = self.get_field_options(field)

if field.field_type in self.FIELD_TYPES:
method = getattr(self,
self.FIELD_TYPES[field.field_type].__name__)
Expand Down Expand Up @@ -163,6 +231,7 @@ def save(self, *args, **kwargs):


class BaseMoloSurveyForm(WagtailAdminPageForm):

def clean(self):
cleaned_data = super(BaseMoloSurveyForm, self).clean()

Expand Down
14 changes: 13 additions & 1 deletion molo/surveys/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# -*- coding: utf-8 -*-

import json
import datetime
from unidecode import unidecode
Expand All @@ -15,6 +17,7 @@
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from django.utils.text import slugify
from django.utils.encoding import smart_str
from django.utils.six import text_type
from modelcluster.fields import ParentalKey
from molo.core.blocks import MarkDownBlock
Expand Down Expand Up @@ -51,6 +54,7 @@
MoloSurveyForm,
PersonalisableMoloSurveyForm,
SurveysFormBuilder,
CHARACTER_COUNT_CHOICE_LIMIT,
)
from .rules import ( # noqa
ArticleTagRule,
Expand Down Expand Up @@ -79,7 +83,7 @@ class Meta:
@property
def clean_name(self):
return str(slugify(text_type(unidecode(
'{} {}'.format(self.pk, self.label.lower())))))
u'{} {}'.format(self.pk, smart_str(self.label))))))


class TermsAndConditionsIndexPage(TranslatablePageMixinNotRoutable, MoloPage):
Expand Down Expand Up @@ -581,6 +585,14 @@ def clean(self):
raise ValidationError(
{'default_value': ["Must be a valid date", ]})

if self.choices and len(self.choices) > CHARACTER_COUNT_CHOICE_LIMIT:
raise ValidationError(
{'field_type': _(
'The combined choices\' maximum characters'
' limit has been exceeded ({max_limit} character(s)).'
).format(max_limit=CHARACTER_COUNT_CHOICE_LIMIT)}
)


SurveyAbstractFormField.panels[4] = SkipLogicStreamPanel('skip_logic')

Expand Down
33 changes: 31 additions & 2 deletions molo/surveys/tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
# -*- coding: utf-8 -*-

from django.core.exceptions import ValidationError
from django.test import TestCase
from molo.core.tests.base import MoloTestCaseMixin
from molo.surveys.blocks import SkipLogicBlock, SkipState
from django.contrib.auth import get_user_model
from molo.surveys.models import (
MoloSurveyFormField,
MoloSurveyPage,
ArticlePage,
MoloSurveyPageView,
MoloSurveySubmission,
SurveysIndexPage,
PersonalisableSurvey,
Expand Down Expand Up @@ -408,7 +413,8 @@ def create_molo_survey_form_field(self, field_type):
admin_label="birthday",
)

def create_personalisable_survey_form_field(self, field_type):
def create_personalisable_survey_form_field(
self, field_type, label="When is your birthday"):
survey = PersonalisableSurvey(
title='Test Survey',
introduction='Introduction to Test Survey ...',
Expand All @@ -419,7 +425,7 @@ def create_personalisable_survey_form_field(self, field_type):

return PersonalisableSurveyFormField.objects.create(
page=survey,
label="When is your birthday",
label=label,
field_type=field_type,
admin_label="birthday",
)
Expand Down Expand Up @@ -472,6 +478,15 @@ def test_datetime_molo_form_fields_not_clean_with_invalid_default(self):

self.assertEqual(e.exception.messages, ['Must be a valid date'])

def test_date_personalisabe_form_str_representation(self):
field = self.create_personalisable_survey_form_field(
'date', label="When is your birthdáy")

self.assertTrue(
'Test Survey - When is your birthd' in
field.__str__()
)

def test_date_personalisabe_form_fields_clean_if_blank(self):
field = self.create_personalisable_survey_form_field('date')
field.default_value = ""
Expand Down Expand Up @@ -520,3 +535,17 @@ def test_datetime_personalisable_fields_not_clean_with_invalid_default(
field.clean()

self.assertEqual(e.exception.messages, ['Must be a valid date'])


class TestMoloSurveyPageView(TestCase, MoloTestCaseMixin):
""" Test case """

def test_model(self):
self.mk_main()
user = get_user_model().objects.create_superuser(
username='superuser',
email='superuser@email.com', password='pass'
)
survey = ArticlePage(title='Test Survey', slug='test-survey')
model = MoloSurveyPageView(user=user, page=survey)
self.assertTrue('superuser viewed Test Survey at' in model.__str__())

0 comments on commit e4c5c60

Please sign in to comment.