Beispiel #1
0
class MyAccountForm(forms.Form):
    first_name = fields.CharField()
    middle_name = fields.CharField(required=False)
    last_name = fields.CharField()
    email = fields.EmailField()
    password = fields.CharField(required=False, widget=forms.PasswordInput())
    preferred_language = fields.ChoiceField(choices=settings.LANGUAGES,
                                            initial=settings.LANGUAGE_CODE)

    def __init__(self, *args, **kwargs):
        self.user = None

        if 'user' in kwargs:
            self.user = kwargs.pop('user')
            kw_initial = kwargs.get('initial', {})
            kwargs['initial'] = {
                'first_name': self.user.first_name,
                'last_name': self.user.last_name,
                'middle_name': self.user.middle_name,
                'email': self.user.email,
                'preferred_language': self.user.preferred_language,
            }
            kwargs['initial'].update(kw_initial)

        super().__init__(*args, **kwargs)
Beispiel #2
0
class AccountsFilterForm(forms.Form):
    STAFF_ONLY = 'STAFF'
    SUPERUSERS_ONLY = 'SUPERUSERS'
    SHOW_ONLY_CHOICES = (
        ('', _('Show Only')),
        (STAFF_ONLY, _('Staff users')),
        (SUPERUSERS_ONLY, _('Superusers')),
    )

    show_only = fields.ChoiceField(choices=SHOW_ONLY_CHOICES, required=False)
Beispiel #3
0
class EventsGalleryForm(forms.Form):
    name = fields.CharField(required=False)
    name_en = fields.CharField(required=False)
    name_fr = fields.CharField(required=False)
    slug = fields.CharField()
    site_id = fields.ChoiceField(
        choices=[(site.id, site.name) for site in Site.objects.all()]
    )

    def __init__(self, request=None, *args, **kwargs):
        self.gallery = None

        if 'gallery' in kwargs:
            self.gallery = kwargs.pop('gallery')
            kw_initial = kwargs.get('initial', {})
            kwargs['initial'] = {
                'name': self.gallery.name,
                'name_en': self.gallery.name_en,
                'name_fr': self.gallery.name_fr,
                'slug': self.gallery.slug,
                'site_id': self.gallery.site_id
            }
            kwargs['initial'].update(kw_initial)

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

    def clean_slug(self):
        data = self.cleaned_data['slug']

        galleries = CorpEventsGallery.objects.all()
        if self.gallery:
            galleries = galleries.exclude(pk=self.gallery.pk)

        try:
            galleries.get(slug=data)
        except CorpEventsGallery.DoesNotExist:
            pass
        else:
            raise forms.ValidationError(_('This slug is already in use.'))

        return data
Beispiel #4
0
    def __init__(self, site=None, request=None, *args, **kwargs):
        self.page = None

        if 'page' in kwargs:
            self.page = kwargs.pop('page')

        p = self.page

        specified_site_id_string = request.GET.get('site', None)

        if specified_site_id_string:
            initial_site_id = specified_site_id_string
        elif p and p.site:
            initial_site_id = p.site.id

        if self.page:
            kw_initial = kwargs.get('initial', {})
            kwargs['initial'] = {
                'name_en': p.name_en,
                'name_fr': p.name_fr,
                'slug': p.slug,
                'parent': p.parent.pk if p.parent else None,
                'show_in_main_menu': p.show_in_main_menu,
                'list_in_main_menu_subnav': p.list_in_main_menu_subnav,
                'name_in_main_menu_subnav_en': p.name_in_main_menu_subnav_en,
                'name_in_main_menu_subnav_fr': p.name_in_main_menu_subnav_fr,
                'show_page_nav': p.show_page_nav,
                'list_in_child_page_nav': p.list_in_child_page_nav,
                'name_in_child_page_nav_en': p.name_in_child_page_nav_en,
                'name_in_child_page_nav_fr': p.name_in_child_page_nav_fr,
                'should_redirect': p.should_redirect,
                'external_redirect': p.external_redirect,
                'internal_redirect': p.internal_redirect.pk if p.internal_redirect else None,
                'opens_in_new_window': p.opens_in_new_window,
                'site_id': int(initial_site_id),
                'facebook_pixel_id': p.facebook_pixel_id
            }
            kwargs['initial'].update(kw_initial)
        else:

            prepop_site = {'site_id': initial_site_id}

            if kwargs.get('initial', {}):
                kwargs['initial'].update(prepop_site)
            else:
                kwargs['initial'] = prepop_site


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

        excludes = Q(parent=None, slug='')
        if self.page:
            excludes |= Q(pk=self.page.pk)
        linkable_pages = CorpPage.objects.exclude(excludes).order_by('full_path')

        if request:
            # import pdb; pdb.set_trace();
            if p and p.site:
                linkable_pages = linkable_pages.filter(site=p.site)
            elif request:
                if specified_site_id_string:
                    linkable_pages = linkable_pages.filter(site_id=specified_site_id_string)
                else:
                    linkable_pages = linkable_pages.filter(site=request.site)
            else:
                pass

        if self.page and self.page.is_locked:
            self.fields.pop('slug')
        else:
            self.fields['parent'] = fields.ChoiceField(
                choices=[(None, 'No parent')] + [(p.pk, '{} ({})'.format(p.full_path, p.site.domain) ) for p in linkable_pages],
                required=False)

        self.fields['internal_redirect'] = fields.ChoiceField(
            choices=[(None, 'No redirect')] + [(p.pk, p.full_path) for p in linkable_pages],
            required=False)
Beispiel #5
0
class PageForm(forms.Form):
    name_en = fields.CharField(label=_('Name'), required=False)
    name_fr = fields.CharField(label=_('Name (French)'), required=False)
    slug = fields.CharField(max_length=64)
    show_in_main_menu = forms.BooleanField(
        label=_('Show in Hamburger Menu'), required=False, initial=True,
        widget=forms.CheckboxInput)
    hidden_bucket = forms.BooleanField(required=False, initial=False)
    list_in_main_menu_subnav = forms.BooleanField(
        label=_('Duplicate in Hamburger Menu Subnav'), required=False, initial=False,
        widget=forms.CheckboxInput)
    name_in_main_menu_subnav_en = fields.CharField(
        label=_('Name in Hamburger Menu Subnav'), required=False)
    name_in_main_menu_subnav_fr = fields.CharField(
        label=_('Name in Hamburger Menu Subnav (French)'), required=False)
    show_page_nav = forms.BooleanField(
        label=_('Show Page Navigation'), required=False, initial=True,
        widget=forms.CheckboxInput)
    list_in_child_page_nav = forms.BooleanField(
        label=_('Show in Child Page Navigation'), required=False, initial=False,
        widget=forms.CheckboxInput)
    name_in_child_page_nav_en = fields.CharField(
        label=_('Name in Child Page Navigation'), required=False)
    name_in_child_page_nav_fr = fields.CharField(
        label=_('Name in Child Page Navigation (French)'), required=False)
    should_redirect = forms.BooleanField(
        required=False, initial=False, widget=forms.CheckboxInput)
    external_redirect = fields.CharField(required=False)
    opens_in_new_window = fields.TypedChoiceField(
        coerce=lambda x: x == 'True', choices=fields.BOOLEAN_CHOICES, initial=False,
        required=False)
    site_id = fields.ChoiceField(
        choices=[
            [s.id, s.domain] for s in Site.objects.all()
        ]
    )
    facebook_pixel_id = fields.CharField(required=False)

    def __init__(self, site=None, request=None, *args, **kwargs):
        self.page = None

        if 'page' in kwargs:
            self.page = kwargs.pop('page')

        p = self.page

        specified_site_id_string = request.GET.get('site', None)

        if specified_site_id_string:
            initial_site_id = specified_site_id_string
        elif p and p.site:
            initial_site_id = p.site.id

        if self.page:
            kw_initial = kwargs.get('initial', {})
            kwargs['initial'] = {
                'name_en': p.name_en,
                'name_fr': p.name_fr,
                'slug': p.slug,
                'parent': p.parent.pk if p.parent else None,
                'show_in_main_menu': p.show_in_main_menu,
                'list_in_main_menu_subnav': p.list_in_main_menu_subnav,
                'name_in_main_menu_subnav_en': p.name_in_main_menu_subnav_en,
                'name_in_main_menu_subnav_fr': p.name_in_main_menu_subnav_fr,
                'show_page_nav': p.show_page_nav,
                'list_in_child_page_nav': p.list_in_child_page_nav,
                'name_in_child_page_nav_en': p.name_in_child_page_nav_en,
                'name_in_child_page_nav_fr': p.name_in_child_page_nav_fr,
                'should_redirect': p.should_redirect,
                'external_redirect': p.external_redirect,
                'internal_redirect': p.internal_redirect.pk if p.internal_redirect else None,
                'opens_in_new_window': p.opens_in_new_window,
                'site_id': int(initial_site_id),
                'facebook_pixel_id': p.facebook_pixel_id
            }
            kwargs['initial'].update(kw_initial)
        else:

            prepop_site = {'site_id': initial_site_id}

            if kwargs.get('initial', {}):
                kwargs['initial'].update(prepop_site)
            else:
                kwargs['initial'] = prepop_site


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

        excludes = Q(parent=None, slug='')
        if self.page:
            excludes |= Q(pk=self.page.pk)
        linkable_pages = CorpPage.objects.exclude(excludes).order_by('full_path')

        if request:
            # import pdb; pdb.set_trace();
            if p and p.site:
                linkable_pages = linkable_pages.filter(site=p.site)
            elif request:
                if specified_site_id_string:
                    linkable_pages = linkable_pages.filter(site_id=specified_site_id_string)
                else:
                    linkable_pages = linkable_pages.filter(site=request.site)
            else:
                pass

        if self.page and self.page.is_locked:
            self.fields.pop('slug')
        else:
            self.fields['parent'] = fields.ChoiceField(
                choices=[(None, 'No parent')] + [(p.pk, '{} ({})'.format(p.full_path, p.site.domain) ) for p in linkable_pages],
                required=False)

        self.fields['internal_redirect'] = fields.ChoiceField(
            choices=[(None, 'No redirect')] + [(p.pk, p.full_path) for p in linkable_pages],
            required=False)

    def clean_parent(self):
        pk = self.cleaned_data['parent']
        parent = None

        if pk:
            try:
                parent = CorpPage.objects.get(pk=pk)
            except CorpPage.DoesNotExist:
                raise forms.ValidationError('Invalid parent.')

        return parent

    def clean_internal_redirect(self):
        pk = self.cleaned_data['internal_redirect']
        parent = None

        if pk:
            try:
                parent = CorpPage.objects.get(pk=pk)
            except CorpPage.DoesNotExist:
                raise forms.ValidationError('Invalid internal redirect.')

        return parent

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

        slug = cleaned_data.get('slug', '')
        parent = cleaned_data.get('parent', None)

        if slug:
            if re.match(r'[^a-zA-Z0-9_-]', slug):
                self.add_error(
                    'slug', forms.ValidationError(_('Slug may only contain alphanumeric '
                                                    'characters, underscore and hyphens.')))
            else:
                pages = CorpPage.objects.filter(parent=parent, slug=slug)

                if self.page:
                    pages = pages.exclude(pk=self.page.pk)

                if pages.exists():
                    self.add_error(
                        'slug', forms.ValidationError(_('This slug is already in use.')))

        return cleaned_data
Beispiel #6
0
    def __init__(self, club, *args, **kwargs):
        self.club = club
        self.page = None

        if 'page' in kwargs:
            self.page = kwargs.pop('page')

        if self.page:
            kw_initial = kwargs.get('initial', {})
            p = self.page
            kwargs['initial'] = {
                'name_en':
                p.name_en,
                'name_fr':
                p.name_fr,
                'slug':
                p.slug,
                'visibility':
                p.visibility,
                'show_address_bar':
                p.show_address_bar,
                'parent':
                p.parent.pk if p.parent else None,
                'show_in_main_menu':
                p.show_in_main_menu,
                'list_in_main_menu_subnav':
                p.list_in_main_menu_subnav,
                'name_in_main_menu_subnav_en':
                p.name_in_main_menu_subnav_en,
                'name_in_main_menu_subnav_fr':
                p.name_in_main_menu_subnav_fr,
                'show_page_nav':
                p.show_page_nav,
                'list_in_child_page_nav':
                p.list_in_child_page_nav,
                'name_in_child_page_nav_en':
                p.name_in_child_page_nav_en,
                'name_in_child_page_nav_fr':
                p.name_in_child_page_nav_fr,
                'alias':
                p.alias.pk if p.alias else None,
                'should_redirect':
                p.should_redirect,
                'external_redirect':
                p.external_redirect,
                'internal_redirect':
                p.internal_redirect.pk if p.internal_redirect else None,
                'opens_in_new_window':
                p.opens_in_new_window,
                'hidden_bucket':
                p.hidden_bucket,
                'facebook_pixel_id':
                p.facebook_pixel_id
            }
            kwargs['initial'].update(kw_initial)

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

        excludes = Q(parent=None, slug='')
        if self.page:
            excludes |= Q(pk=self.page.pk)
        linkable_pages = self.club.pages.exclude(excludes).order_by(
            'full_path')

        if self.page and self.page.is_locked:
            self.fields.pop('slug')
        else:
            self.fields['parent'] = fields.ChoiceField(
                choices=[(None, 'No parent')] + [(p.pk, p.full_path)
                                                 for p in linkable_pages],
                required=False)

        self.fields['alias'] = fields.ChoiceField(
            choices=[(None, 'No alias')] + [(p.pk, p.full_path)
                                            for p in linkable_pages],
            required=False)

        self.fields['internal_redirect'] = fields.ChoiceField(
            choices=[(None, 'No redirect')] + [(p.pk, p.full_path)
                                               for p in linkable_pages],
            required=False)
Beispiel #7
0
class PageForm(forms.Form):
    name_en = fields.CharField(label=_('Name'), required=False)
    name_fr = fields.CharField(label=_('Name (French)'), required=False)
    slug = fields.CharField(max_length=64)
    visibility = fields.ChoiceField(choices=ClubPage.VISIBILITY_CHOICES)
    show_address_bar = fields.TypedChoiceField(coerce=lambda x: x == 'True',
                                               choices=fields.BOOLEAN_CHOICES,
                                               initial=True,
                                               required=False)
    show_in_main_menu = forms.BooleanField(label=_('Show in Hamburger Menu'),
                                           required=False,
                                           initial=True,
                                           widget=forms.CheckboxInput)
    list_in_main_menu_subnav = forms.BooleanField(
        label=_('Duplicate in Hamburger Menu Subnav'),
        required=False,
        initial=False,
        widget=forms.CheckboxInput)
    name_in_main_menu_subnav_en = fields.CharField(
        label=_('Name in Hamburger Menu Subnav'), required=False)
    name_in_main_menu_subnav_fr = fields.CharField(
        label=_('Name in Hamburger Menu Subnav (French)'), required=False)
    show_page_nav = forms.BooleanField(label=_('Show Page Navigation'),
                                       required=False,
                                       initial=True,
                                       widget=forms.CheckboxInput)
    list_in_child_page_nav = forms.BooleanField(
        label=_('Show in Child Page Navigation'),
        required=False,
        initial=False,
        widget=forms.CheckboxInput)
    name_in_child_page_nav_en = fields.CharField(
        label=_('Name in Child Page Navigation'), required=False)
    name_in_child_page_nav_fr = fields.CharField(
        label=_('Name in Child Page Navigation (French)'), required=False)
    should_redirect = forms.BooleanField(required=False,
                                         initial=False,
                                         widget=forms.CheckboxInput)
    external_redirect = fields.CharField(required=False)
    opens_in_new_window = fields.TypedChoiceField(
        coerce=lambda x: x == 'True',
        choices=fields.BOOLEAN_CHOICES,
        initial=False,
        required=False)
    hidden_bucket = forms.BooleanField(required=False, initial=False)
    facebook_pixel_id = fields.CharField(required=False)

    def __init__(self, club, *args, **kwargs):
        self.club = club
        self.page = None

        if 'page' in kwargs:
            self.page = kwargs.pop('page')

        if self.page:
            kw_initial = kwargs.get('initial', {})
            p = self.page
            kwargs['initial'] = {
                'name_en':
                p.name_en,
                'name_fr':
                p.name_fr,
                'slug':
                p.slug,
                'visibility':
                p.visibility,
                'show_address_bar':
                p.show_address_bar,
                'parent':
                p.parent.pk if p.parent else None,
                'show_in_main_menu':
                p.show_in_main_menu,
                'list_in_main_menu_subnav':
                p.list_in_main_menu_subnav,
                'name_in_main_menu_subnav_en':
                p.name_in_main_menu_subnav_en,
                'name_in_main_menu_subnav_fr':
                p.name_in_main_menu_subnav_fr,
                'show_page_nav':
                p.show_page_nav,
                'list_in_child_page_nav':
                p.list_in_child_page_nav,
                'name_in_child_page_nav_en':
                p.name_in_child_page_nav_en,
                'name_in_child_page_nav_fr':
                p.name_in_child_page_nav_fr,
                'alias':
                p.alias.pk if p.alias else None,
                'should_redirect':
                p.should_redirect,
                'external_redirect':
                p.external_redirect,
                'internal_redirect':
                p.internal_redirect.pk if p.internal_redirect else None,
                'opens_in_new_window':
                p.opens_in_new_window,
                'hidden_bucket':
                p.hidden_bucket,
                'facebook_pixel_id':
                p.facebook_pixel_id
            }
            kwargs['initial'].update(kw_initial)

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

        excludes = Q(parent=None, slug='')
        if self.page:
            excludes |= Q(pk=self.page.pk)
        linkable_pages = self.club.pages.exclude(excludes).order_by(
            'full_path')

        if self.page and self.page.is_locked:
            self.fields.pop('slug')
        else:
            self.fields['parent'] = fields.ChoiceField(
                choices=[(None, 'No parent')] + [(p.pk, p.full_path)
                                                 for p in linkable_pages],
                required=False)

        self.fields['alias'] = fields.ChoiceField(
            choices=[(None, 'No alias')] + [(p.pk, p.full_path)
                                            for p in linkable_pages],
            required=False)

        self.fields['internal_redirect'] = fields.ChoiceField(
            choices=[(None, 'No redirect')] + [(p.pk, p.full_path)
                                               for p in linkable_pages],
            required=False)

    def clean_parent(self):
        pk = self.cleaned_data['parent']
        parent = None

        if pk:
            try:
                parent = ClubPage.objects.get(pk=pk)
            except ClubPage.DoesNotExist:
                raise forms.ValidationError('Invalid parent.')

        return parent

    def clean_alias(self):
        pk = self.cleaned_data['alias']
        parent = None

        if pk:
            try:
                parent = ClubPage.objects.get(pk=pk)
            except ClubPage.DoesNotExist:
                raise forms.ValidationError('Invalid alias.')

        return parent

    def clean_internal_redirect(self):
        pk = self.cleaned_data['internal_redirect']
        parent = None

        if pk:
            try:
                parent = ClubPage.objects.get(pk=pk)
            except ClubPage.DoesNotExist:
                raise forms.ValidationError('Invalid redirect.')

        return parent

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

        slug = cleaned_data.get('slug', '')
        parent = cleaned_data.get('parent', None)

        if slug:
            if re.match(r'[^a-zA-Z0-9_-]', slug):
                self.add_error(
                    'slug',
                    forms.ValidationError(
                        _('Slug may only contain alphanumeric '
                          'characters, underscore and hyphens.')))
            else:
                pages = ClubPage.objects.filter(club=self.club,
                                                parent=parent,
                                                slug=slug)

                if self.page:
                    pages = pages.exclude(pk=self.page.pk)

                if pages.exists():
                    self.add_error(
                        'slug',
                        forms.ValidationError(
                            _('This slug is already in use.')))

        return cleaned_data
Beispiel #8
0
class CalendarForm(forms.Form):
    # extra_fields
    recurrence_set = forms.BooleanField(label=_('Set recurrence parameters'),
                                        required=False,
                                        initial=False,
                                        widget=forms.CheckboxInput)
    recurrence_pattern = forms.ChoiceField(label=_('Pattern'),
                                           choices=RECURRENCE_PATTERN,
                                           required=False)
    recurrence_every = forms.IntegerField(label=_('Event happens every'),
                                          required=False)
    recurrence_repetition_types = forms.ChoiceField(
        label=_('Recurrence type'),
        required=False,
        choices=RECURRENCE_REPETITION_TYPES)
    recurrence_until = forms.DateField(label=_('Until'),
                                       required=False,
                                       initial=None,
                                       widget=forms.SelectDateWidget())
    recurrence_repetitions = forms.IntegerField(label=_('Repetitions'),
                                                required=False)

    type = fields.ChoiceField(choices=ClubEvent.TYPE_CHOICES)
    name = fields.CharField()
    email = fields.EmailField(required=False)
    description = fields.TextareaField(widget=forms.Textarea(
        attrs={'data-tinymce': True}))
    start_date = forms.DateField(widget=forms.SelectDateWidget())
    start_time = forms.TimeField(initial=DEFAULT_START_TIME,
                                 widget=SelectTimeWidget(required=False,
                                                         twelve_hr=True))
    end_date = forms.DateField(required=False,
                               initial=None,
                               widget=forms.SelectDateWidget())
    end_time = forms.TimeField(required=False,
                               initial=DEFAULT_END_TIME,
                               widget=SelectTimeWidget(required=False,
                                                       twelve_hr=True))
    max_attendees = fields.IntegerField(initial=0)
    max_guests_per_rsvp = fields.IntegerField(initial=1, min_value=1)
    photo = forms.ImageField(required=False)
    custom_question_1 = fields.CharField(required=False)
    custom_question_2 = fields.CharField(required=False)
    custom_question_3 = fields.CharField(required=False)
    custom_question_4 = fields.CharField(required=False)
    custom_question_5 = fields.CharField(required=False)
    online_registration = fields.TypedChoiceField(
        coerce=lambda x: x == 'True',
        choices=fields.BOOLEAN_CHOICES,
        initial=True,
        required=False)
    registration_open_date = forms.DateField(required=False,
                                             initial=None,
                                             widget=forms.SelectDateWidget())
    registration_open_time = forms.TimeField(
        required=False,
        initial=DEFAULT_REGISTRATION_OPEN_TIME,
        widget=SelectTimeWidget(required=False, twelve_hr=True))
    registration_close_date = forms.DateField(required=False,
                                              initial=None,
                                              widget=forms.SelectDateWidget())
    registration_close_time = forms.TimeField(
        required=False,
        initial=DEFAULT_REGISTRATION_CLOSE_TIME,
        widget=SelectTimeWidget(required=False, twelve_hr=True))

    def __init__(self, *args, **kwargs):
        self.event = None

        if 'event' in kwargs:
            self.event = kwargs.pop('event')

        if self.event:
            kw_initial = kwargs.get('initial', {})
            kwargs['initial'] = {
                'start_date': self.event.start_date,
                'start_time': self.event.start_time,
                'end_date': self.event.end_date,
                'end_time': self.event.end_time,
                'name': self.event.name,
                'email': self.event.email,
                'description': self.event.description,
                'type': self.event.type,
                'max_attendees': self.event.max_attendees,
                'max_guests_per_rsvp': self.event.max_guests_per_rsvp,
                'custom_question_1': self.event.custom_question_1,
                'custom_question_2': self.event.custom_question_2,
                'custom_question_3': self.event.custom_question_3,
                'custom_question_4': self.event.custom_question_4,
                'custom_question_5': self.event.custom_question_5,
                'online_registration': self.event.online_registration,
                'registration_open_date': self.event.registration_open_date,
                'registration_open_time': self.event.registration_open_time,
                'registration_close_date': self.event.registration_close_date,
                'registration_close_time': self.event.registration_close_time
            }
            kwargs['initial'].update(kw_initial)

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

    def clean(self):
        cleaned_data = self.cleaned_data

        start_date = self.cleaned_data['start_date']
        start_time = self.cleaned_data['start_time']

        if self.cleaned_data.get('recurrence_set'):
            if not self.cleaned_data.get('recurrence_pattern'):
                self.add_error(
                    'recurrence_pattern',
                    forms.ValidationError(_('This is a required field.')))

            if not self.cleaned_data.get('recurrence_every'):
                self.add_error(
                    'recurrence_every',
                    forms.ValidationError(_('This is a required field.')))

            if self.cleaned_data.get('recurrence_repetition_types') == REPETITION_UNTIL \
                    and not self.cleaned_data.get('recurrence_until'):
                self.add_error(
                    'recurrence_until',
                    forms.ValidationError(_('This is a required field.')))

            if self.cleaned_data.get('recurrence_repetition_types') == NB_REPETITIONS \
                    and not self.cleaned_data.get('recurrence_repetitions'):
                self.add_error(
                    'recurrence_repetitions',
                    forms.ValidationError(_('This is a required field.')))

        if not self.cleaned_data.get('end_date'):
            self.cleaned_data['end_date'] = start_date

        if not self.cleaned_data.get('end_time'):
            self.cleaned_data['end_time'] = start_time

        end_date = self.cleaned_data['end_date']
        end_time = self.cleaned_data['end_time']
        email = self.cleaned_data['email']

        if end_date < start_date:
            self.add_error(
                'end_date',
                forms.ValidationError(
                    _('End date must not be earlier than start date.')))

        if start_date == end_date and end_time < start_time:
            self.add_error(
                'end_time',
                forms.ValidationError(
                    _('End time must not be earlier than start time.')))

        open_date = self.cleaned_data.get('registration_open_date')
        open_time = self.cleaned_data.get('registration_open_time')
        close_date = self.cleaned_data.get('registration_close_date')
        close_time = self.cleaned_data.get('registration_close_time')

        online_registration = self.cleaned_data.get('online_registration')

        if online_registration:
            if not open_date:
                self.add_error(
                    'registration_open_date',
                    forms.ValidationError(_('This field is required.')))
            if not open_time:
                self.add_error(
                    'registration_open_time',
                    forms.ValidationError(_('This field is required.')))
            if not close_date:
                self.add_error(
                    'registration_close_date',
                    forms.ValidationError(_('This field is required.')))
            if not close_time:
                self.add_error(
                    'registration_close_time',
                    forms.ValidationError(_('This field is required.')))

            if open_date and open_time and close_date and close_time:
                if open_date > end_date:
                    self.add_error(
                        'registration_open_date',
                        forms.ValidationError(
                            _('Open date must not be later than end date.')))

                if close_date > end_date:
                    self.add_error(
                        'registration_close_date',
                        forms.ValidationError(
                            _('Close date must not be later than end date.')))

                if close_date < open_date:
                    self.add_error(
                        'registration_close_date',
                        forms.ValidationError(
                            _('Close date must not be earlier than open date.')
                        ))

                if open_date == close_date and close_time < open_time:
                    self.add_error(
                        'registration_close_time',
                        forms.ValidationError(
                            _('Close time must not be earlier than open time.')
                        ))

        photo = self.cleaned_data.get('photo', False)
        if photo and photo._size > 4 * 1024 * 1024:
            self.add_error(
                'photo', forms.ValidationError(_('Image too large( > 4MB )')))

        return cleaned_data
Beispiel #9
0
class UserForm(forms.Form):
    username = fields.CharField(max_length=48)
    password = fields.CharField(min_length=6,
                                required=False,
                                widget=forms.PasswordInput())
    first_name = fields.CharField(required=False)
    last_name = fields.CharField(required=False)
    middle_name = fields.CharField(required=False)
    email = fields.EmailField()
    membership_number = fields.CharField(max_length=15, required=False)
    employee_number = fields.CharField(max_length=15, required=False)
    is_superuser = fields.TypedChoiceField(coerce=lambda x: x == 'True',
                                           choices=fields.BOOLEAN_CHOICES,
                                           initial=False,
                                           required=False)
    is_staff = fields.TypedChoiceField(coerce=lambda x: x == 'True',
                                       choices=fields.BOOLEAN_CHOICES,
                                       initial=False,
                                       required=False)
    preferred_language = fields.ChoiceField(choices=settings.LANGUAGES,
                                            initial=settings.LANGUAGE_CODE)
    status = fields.ChoiceField(choices=User.STATUSES)
    clubcorp = fields.ChoiceField(choices=[(None, '')], required=False)
    clubcorp_number = fields.CharField(max_length=5, required=False)
    type = fields.ChoiceField(choices=[(None, '')], required=False)
    category = fields.ChoiceField(choices=[(None, '')], required=False)
    home_club = fields.ChoiceField(choices=[(None, '')], required=False)
    option_club = fields.ChoiceField(choices=[(None, '')], required=False)
    home_club_alternate_1 = fields.ChoiceField(choices=[(None, '')],
                                               required=False)
    home_club_alternate_2 = fields.ChoiceField(choices=[(None, '')],
                                               required=False)

    def __init__(self, *args, **kwargs):
        self.user = None

        if kwargs.get('user'):
            self.user = kwargs.pop('user')
            kw_initial = kwargs.get('initial', {})
            kwargs['initial'] = {
                'username':
                self.user.username,
                'first_name':
                self.user.first_name,
                'last_name':
                self.user.last_name,
                'middle_name':
                self.user.middle_name,
                'email':
                self.user.email,
                'membership_number':
                self.user.membership_number,
                'employee_number':
                self.user.employee_number,
                'is_superuser':
                self.user.is_superuser,
                'is_staff':
                self.user.is_staff,
                'preferred_language':
                self.user.preferred_language,
                'status':
                self.user.status,
                'clubcorp':
                getattr(self.user.home_club, 'id', None),
                'clubcorp_number':
                self.user.clubcorp_number,
                'category':
                getattr(self.user.category, 'id', None),
                'type':
                getattr(self.user.type, 'id', None),
                'home_club':
                getattr(self.user.home_club, 'pk', None),
                'option_club':
                getattr(self.user.option_club, 'pk', None),
                'home_club_alternate_1':
                getattr(self.user.home_club_alternate_1, 'pk', None),
                'home_club_alternate_2':
                getattr(self.user.home_club_alternate_2, 'pk', None),
            }
            kwargs['initial'].update(kw_initial)

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

        self.fields['clubcorp'].choices += [(c.id, c.name)
                                            for c in ClubCorp.objects.all()]
        self.fields['type'].choices += [(t.id, t.name)
                                        for t in UserType.objects.all()]
        self.fields['clubcorp'].choices += [
            (c.id, c.name) for c in UserCategory.objects.all()
        ]

        self.fields['home_club'].choices += [(c.pk, c.name)
                                             for c in Club.objects.all()]
        self.fields['option_club'].choices += [(c.pk, c.name)
                                               for c in Club.objects.all()]
        self.fields['home_club_alternate_1'].choices += [
            (c.pk, c.name) for c in Club.objects.all()
        ]
        self.fields['home_club_alternate_2'].choices += [
            (c.pk, c.name) for c in Club.objects.all()
        ]

    def clean_username(self):
        data = self.cleaned_data['username']

        users = User.objects.all()

        if self.user:
            users = users.exclude(pk=self.user.pk)

        try:
            users.get(username=data)
        except User.DoesNotExist:
            pass
        else:
            raise forms.ValidationError(_('Username is already in use.'))

        return data

    def clean_password(self):
        data = self.cleaned_data['password']
        return data if data else None

    def clean_membership_number(self):
        data = self.cleaned_data['membership_number']
        return data if data else None

    def clean_employee_number(self):
        data = self.cleaned_data['employee_number']
        return data if data else None

    def clean_is_staff(self):
        is_superuser = self.cleaned_data['is_superuser']
        is_staff = self.cleaned_data['is_staff']
        return is_staff or is_superuser

    def validate_fk(self, data, klass):
        if data:
            try:
                data = klass.objects.get(pk=data)
            except klass.DoesNotExist:
                raise forms.ValidationError(_('Invalid entry.'))
        else:
            data = None
        return data

    def clean_clubcorp(self):
        data = self.cleaned_data['clubcorp']
        return self.validate_fk(data, ClubCorp)

    def clean_category(self):
        data = self.cleaned_data['category']
        return self.validate_fk(data, UserCategory)

    def clean_type(self):
        data = self.cleaned_data['type']
        return self.validate_fk(data, UserType)

    def clean_home_club(self):
        data = self.cleaned_data['home_club']
        return self.validate_fk(data, Club)

    def clean_option_club(self):
        data = self.cleaned_data['option_club']
        return self.validate_fk(data, Club)

    def clean_home_club_alternate_1(self):
        data = self.cleaned_data['home_club_alternate_1']
        return self.validate_fk(data, Club)

    def clean_home_club_alternate_2(self):
        data = self.cleaned_data['home_club_alternate_2']
        return self.validate_fk(data, Club)