예제 #1
0
class SimpleStatisticsForm(forms.Form):

    from_date = forms.SplitDateTimeField(widget=SplitHiddenDateWidget(
        default_time='00:00'))
    to_date = forms.SplitDateTimeField(widget=SplitHiddenDateWidget(
        default_time='23:59'))
예제 #2
0
class RestraintInjuryForm(ModelForm):

    pt_id = forms.IntegerField(
        min_value=99999,
        max_value=999999,
        error_messages={
            'min_value': 'Please enter a valid UHID',
            'max_value': 'Please enter a valid UHID'
        },
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'UHID eg: 182029'
        }),
        label='Patient UHID')
    pt_name = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Eg: Ajay Philip'
        }),
        label='Patient Name')
    pt_location = forms.ModelChoiceField(
        queryset=Locations.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Location',
        empty_label=('Unselected'))
    pt_gender = forms.CharField(max_length=50,
                                widget=forms.Select(
                                    choices=ReturnToICU.CHOICES,
                                    attrs={'class': 'form-control'}),
                                label='Patient Gender')
    pt_age = forms.IntegerField(
        min_value=0,
        max_value=200,
        error_messages={
            'min_value': 'Please enter a valid UHID',
            'max_value': 'Please enter a valid UHID'
        },
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'EG: 60'
        }),
        label='Patient Age')
    pt_doctor = forms.ModelChoiceField(
        queryset=Doctors.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Doctor',
        empty_label=('Unselected'))
    pt_diagnosis = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='Diagnosis')

    pt_department = forms.ModelChoiceField(
        queryset=Departments.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Department',
        empty_label=('Unselected'))

    dateofadmission = forms.DateField(widget=AdminDateWidget(),
                                      label="Date of Admission")

    indicationof_restraint = forms.CharField(
        max_length=200,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Please provide indication details'
            }),
        label='Indication of Restraint')

    datetime_restraintstart = forms.SplitDateTimeField(
        widget=CustomAdminSplitDateTime(),
        label='Date and Time of Restrain Start:')

    datetime_restraintremoval = forms.SplitDateTimeField(
        widget=CustomAdminSplitDateTime(),
        label='Date and Time of Restrain End:')

    obtain_consent = forms.CharField(max_length=50,
                                     widget=forms.Select(
                                         choices=RestraintInjury.YesNo,
                                         attrs={'class': 'form-control'}),
                                     label='Obtain Consent?')

    maintain_observation = forms.CharField(
        max_length=50,
        widget=forms.Select(choices=RestraintInjury.YesNo,
                            attrs={'class': 'form-control'}),
        label='Obtain Observation Chart?')

    injury = forms.CharField(max_length=50,
                             widget=forms.Select(
                                 choices=RestraintInjury.YesNo,
                                 attrs={'class': 'form-control'}),
                             label='Injury?')

    injury_details = forms.CharField(
        required=False,
        widget=forms.Textarea(
            attrs={
                'class': 'form-control',
                'placeholder': "Please provide comments if 'yes' for injury"
            }),
        label='Injury Details')

    report_by = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Nurse Name'
        }),
        label='Report By')

    class Meta:
        model = RestraintInjury
        fields = [
            'pt_id', 'pt_name', 'pt_location', 'pt_gender', 'pt_age',
            'pt_doctor', 'pt_diagnosis', 'pt_department', 'dateofadmission',
            'indicationof_restraint', 'datetime_restraintstart',
            'datetime_restraintremoval', 'obtain_consent',
            'maintain_observation', 'injury', 'injury_details', 'report_by'
        ]

        exclude = ['timestamp']
예제 #3
0
class CourseModeForm(forms.ModelForm):
    """
    Admin form for adding a course mode.
    """
    class Meta(object):
        model = CourseMode
        fields = '__all__'

    mode_slug = forms.ChoiceField(choices=COURSE_MODE_SLUG_CHOICES,
                                  label=_("Mode"))

    # The verification deadline is stored outside the course mode in the verify_student app.
    # (we used to use the course mode expiration_datetime as both an upgrade and verification deadline).
    # In order to make this transition easier, we include the verification deadline as a custom field
    # in the course mode admin form.  Longer term, we will deprecate the course mode Django admin
    # form in favor of an external Course Administration Tool.
    verification_deadline = forms.SplitDateTimeField(
        label=_("Verification Deadline"),
        required=False,
        help_text=_(
            "OPTIONAL: After this date/time, users will no longer be able to submit photos for verification.  "
            "This appies ONLY to modes that require verification."),
        widget=admin.widgets.AdminSplitDateTime,
    )

    def __init__(self, *args, **kwargs):
        # If args is a QueryDict, then the ModelForm addition request came in as a POST with a course ID string.
        # Change the course ID string to a CourseLocator object by copying the QueryDict to make it mutable.
        if args and 'course' in args[0] and isinstance(args[0], QueryDict):
            args_copy = args[0].copy()
            args_copy['course'] = CourseKey.from_string(args_copy['course'])
            args = [args_copy]

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

        try:
            if self.data.get('course'):
                self.data['course'] = CourseKey.from_string(
                    self.data['course'])
        except AttributeError:
            # Change the course ID string to a CourseLocator.
            # On a POST request, self.data is a QueryDict and is immutable - so this code will fail.
            # However, the args copy above before the super() call handles this case.
            pass

        default_tz = timezone(settings.TIME_ZONE)

        if self.instance._expiration_datetime:  # pylint: disable=protected-access
            # django admin is using default timezone. To avoid time conversion from db to form
            # convert the UTC object to naive and then localize with default timezone.
            _expiration_datetime = self.instance._expiration_datetime.replace(  # pylint: disable=protected-access
                tzinfo=None)
            self.initial["_expiration_datetime"] = default_tz.localize(
                _expiration_datetime)
        # Load the verification deadline
        # Since this is stored on a model in verify student, we need to load it from there.
        # We need to munge the timezone a bit to get Django admin to display it without converting
        # it to the user's timezone.  We'll make sure we write it back to the database with the timezone
        # set to UTC later.
        if self.instance.course_id and self.instance.mode_slug in CourseMode.VERIFIED_MODES:
            deadline = verification_models.VerificationDeadline.deadline_for_course(
                self.instance.course_id)
            self.initial["verification_deadline"] = (default_tz.localize(
                deadline.replace(
                    tzinfo=None)) if deadline is not None else None)

    def clean_course_id(self):
        """
        Validate the course id
        """
        return clean_course_id(self)

    def clean__expiration_datetime(self):
        """
        Ensure that the expiration datetime we save uses the UTC timezone.
        """
        # django admin saving the date with default timezone to avoid time conversion from form to db
        # changes its tzinfo to UTC
        if self.cleaned_data.get("_expiration_datetime"):
            return self.cleaned_data.get("_expiration_datetime").replace(
                tzinfo=UTC)

    def clean_verification_deadline(self):
        """
        Ensure that the verification deadline we save uses the UTC timezone.
        """
        if self.cleaned_data.get("verification_deadline"):
            return self.cleaned_data.get("verification_deadline").replace(
                tzinfo=UTC)

    def clean(self):
        """
        Clean the form fields.
        This is the place to perform checks that involve multiple form fields.
        """
        cleaned_data = super(CourseModeForm, self).clean()
        mode_slug = cleaned_data.get("mode_slug")
        upgrade_deadline = cleaned_data.get("_expiration_datetime")
        verification_deadline = cleaned_data.get("verification_deadline")

        # Allow upgrade deadlines ONLY for the "verified" mode
        # This avoids a nasty error condition in which the upgrade deadline is set
        # for a professional education course before the enrollment end date.
        # When this happens, the course mode expires and students are able to enroll
        # in the course for free.  To avoid this, we explicitly prevent admins from
        # setting an upgrade deadline for any mode except "verified" (which has an upgrade path).
        if upgrade_deadline is not None and mode_slug != CourseMode.VERIFIED:
            raise forms.ValidationError(
                'Only the "verified" mode can have an upgrade deadline.  '
                'For other modes, please set the enrollment end date in Studio.'
            )

        # Verification deadlines are allowed only for verified modes
        if verification_deadline is not None and mode_slug not in CourseMode.VERIFIED_MODES:
            raise forms.ValidationError(
                "Verification deadline can be set only for verified modes.")

        # Verification deadline must be after the upgrade deadline,
        # if an upgrade deadline is set.
        # There are cases in which we might want to set a verification deadline,
        # but not an upgrade deadline (for example, a professional education course that requires verification).
        if verification_deadline is not None:
            if upgrade_deadline is not None and verification_deadline < upgrade_deadline:
                raise forms.ValidationError(
                    "Verification deadline must be after the upgrade deadline."
                )

        return cleaned_data

    def save(self, commit=True):
        """
        Save the form data.
        """
        # Trigger validation so we can access cleaned data
        if self.is_valid():
            course = self.cleaned_data.get("course")
            verification_deadline = self.cleaned_data.get(
                "verification_deadline")
            mode_slug = self.cleaned_data.get("mode_slug")

            # Since the verification deadline is stored in a separate model,
            # we need to handle saving this ourselves.
            # Note that verification deadline can be `None` here if
            # the deadline is being disabled.
            if course is not None and mode_slug in CourseMode.VERIFIED_MODES:
                verification_models.VerificationDeadline.set_deadline(
                    course.id, verification_deadline)

        return super(CourseModeForm, self).save(commit=commit)
예제 #4
0
class ReservationForm(forms.Form):
    """
    This is the  form for reservation.
    """
    error_messages = {
        'date_time_error': 'Departure time earlier than Arrival time',
    }
    first_name = forms.CharField(
        label=_("First Name"),
        max_length=50,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter first name'),
        }))
    middle_name = forms.CharField(
        label=_('Middle Name'),
        required=False,
        max_length=50,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter middle name'),
        }))
    last_name = forms.CharField(
        label=_("Last Name"),
        max_length=50,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter last name'),
        }))
    contact_no = forms.CharField(
        label=_('Contact No'),
        max_length=15,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter contact number'),
        }))
    email = forms.EmailField(
        label=_("Email"),
        max_length=50,
        required=False,
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter email'),
        }))
    address = forms.CharField(
        label=_("Address"),
        max_length=50,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter address'),
        }))
    # no_of_children = forms.IntegerField(
    #     widget=forms.NumberInput(
    #         attrs={
    #             'class': 'form-control',
    #             'placeholder': _('Enter number of children'),
    #         }
    #     )
    # )
    # no_of_adults = forms.IntegerField(
    #     widget=forms.NumberInput(
    #         attrs={
    #             'class': 'form-control',
    #             'placeholder': _('Enter number of adults'),
    #         }
    #     )
    # )
    rooms = forms.ModelMultipleChoiceField(
        queryset=Room.objects.filter(reservation__isnull=True),
        widget=FilteredSelectMultiple(
            is_stacked=True,
            verbose_name="Rooms",
            attrs={
                'class': 'form-control',
            },
        ),
    )
    expected_arrival_date_time = forms.SplitDateTimeField(
        widget=MySplitDateTime())

    expected_departure_date_time = forms.SplitDateTimeField(
        widget=MySplitDateTime())
예제 #5
0
class MockNowForm(forms.Form):
    new_date = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime,
                                        label="Change current time")

    def save(self):
        core.set_mock_now(self.cleaned_data['new_date'])
예제 #6
0
class PersonForm(CruditorTapeformMixin, forms.ModelForm):
    reminder = forms.SplitDateTimeField()

    class Meta:
        model = Person
        fields = '__all__'
예제 #7
0
class EventCancelForm(forms.Form):
    subevent = forms.ModelChoiceField(SubEvent.objects.none(),
                                      label=pgettext_lazy('subevent', 'Date'),
                                      required=False,
                                      empty_label=pgettext_lazy(
                                          'subevent', 'All dates'))
    all_subevents = forms.BooleanField(
        label=_('Cancel all dates'),
        initial=False,
        required=False,
    )
    subevents_from = forms.SplitDateTimeField(
        widget=SplitDateTimePickerWidget(
            attrs={
                'data-inverse-dependency': '#id_all_subevents',
            }),
        label=pgettext_lazy('subevent', 'All dates starting at or after'),
        required=False,
    )
    subevents_to = forms.SplitDateTimeField(
        widget=SplitDateTimePickerWidget(
            attrs={
                'data-inverse-dependency': '#id_all_subevents',
            }),
        label=pgettext_lazy('subevent', 'All dates starting before'),
        required=False,
    )
    auto_refund = forms.BooleanField(
        label=_('Automatically refund money if possible'),
        initial=True,
        required=False)
    manual_refund = forms.BooleanField(
        label=
        _('Create manual refund if the payment method odes not support automatic refunds'
          ),
        widget=forms.CheckboxInput(
            attrs={'data-display-dependency': '#id_auto_refund'}),
        initial=True,
        required=False,
        help_text=
        _('If checked, all payments with a payment method not supporting automatic refunds will be on your '
          'manual refund to-do list. Do not check if you want to refund some of the orders by offsetting '
          'with different orders or issuing gift cards.'))
    refund_as_giftcard = forms.BooleanField(
        label=
        _('Refund order value to a gift card instead instead of the original payment method'
          ),
        widget=forms.CheckboxInput(
            attrs={'data-display-dependency': '#id_auto_refund'}),
        initial=False,
        required=False,
    )
    gift_card_expires = SplitDateTimeField(
        label=_('Gift card validity'),
        required=False,
        widget=SplitDateTimePickerWidget(
            attrs={'data-display-dependency': '#id_refund_as_giftcard'}, ))
    gift_card_conditions = forms.CharField(
        label=_('Special terms and conditions'),
        required=False,
        widget=forms.Textarea(attrs={
            'rows':
            2,
            'data-display-dependency':
            '#id_refund_as_giftcard'
        }, ))
    keep_fee_fixed = forms.DecimalField(
        label=_("Keep a fixed cancellation fee"),
        max_digits=10,
        decimal_places=2,
        required=False)
    keep_fee_per_ticket = forms.DecimalField(
        label=_("Keep a fixed cancellation fee per ticket"),
        help_text=_("Free tickets and add-on products are not counted"),
        max_digits=10,
        decimal_places=2,
        required=False)
    keep_fee_percentage = forms.DecimalField(
        label=_("Keep a percentual cancellation fee"),
        max_digits=10,
        decimal_places=2,
        required=False)
    keep_fees = forms.MultipleChoiceField(
        label=_("Keep fees"),
        widget=forms.CheckboxSelectMultiple,
        choices=[(k, v) for k, v in OrderFee.FEE_TYPES
                 if k != OrderFee.FEE_TYPE_GIFTCARD],
        help_text=
        _('The selected types of fees will not be refunded but instead added to the cancellation fee. Fees '
          'are never refunded in when an order in an event series is only partially canceled since it '
          'consists of tickets for multiple dates.'),
        required=False,
    )
    send = forms.BooleanField(label=_("Send information via email"),
                              required=False)
    send_subject = forms.CharField()
    send_message = forms.CharField()
    send_waitinglist = forms.BooleanField(
        label=_("Send information to waiting list"), required=False)
    send_waitinglist_subject = forms.CharField()
    send_waitinglist_message = forms.CharField()

    def _set_field_placeholders(self, fn, base_parameters):
        phs = [
            '{%s}' % p for p in sorted(
                get_available_placeholders(self.event, base_parameters).keys())
        ]
        ht = _('Available placeholders: {list}').format(list=', '.join(phs))
        if self.fields[fn].help_text:
            self.fields[fn].help_text += ' ' + str(ht)
        else:
            self.fields[fn].help_text = ht
        self.fields[fn].validators.append(PlaceholderValidator(phs))

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        kwargs.setdefault('initial', {})
        kwargs['initial'][
            'gift_card_expires'] = self.event.organizer.default_gift_card_expiry
        super().__init__(*args, **kwargs)
        self.fields['send_subject'] = I18nFormField(
            label=_("Subject"),
            required=True,
            widget_kwargs={'attrs': {
                'data-display-dependency': '#id_send'
            }},
            initial=_('Canceled: {event}'),
            widget=I18nTextInput,
            locales=self.event.settings.get('locales'),
        )
        self.fields['send_message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea,
            required=True,
            widget_kwargs={'attrs': {
                'data-display-dependency': '#id_send'
            }},
            locales=self.event.settings.get('locales'),
            initial=LazyI18nString.from_gettext(
                gettext_noop(
                    'Hello,\n\n'
                    'with this email, we regret to inform you that {event} has been canceled.\n\n'
                    'We will refund you {refund_amount} to your original payment method.\n\n'
                    'You can view the current state of your order here:\n\n{url}\n\nBest regards,\n\n'
                    'Your {event} team')))

        self._set_field_placeholders('send_subject', [
            'event_or_subevent', 'refund_amount', 'position_or_address',
            'order', 'event'
        ])
        self._set_field_placeholders('send_message', [
            'event_or_subevent', 'refund_amount', 'position_or_address',
            'order', 'event'
        ])
        self.fields['send_waitinglist_subject'] = I18nFormField(
            label=_("Subject"),
            required=True,
            initial=_('Canceled: {event}'),
            widget=I18nTextInput,
            widget_kwargs={
                'attrs': {
                    'data-display-dependency': '#id_send_waitinglist'
                }
            },
            locales=self.event.settings.get('locales'),
        )
        self.fields['send_waitinglist_message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea,
            required=True,
            locales=self.event.settings.get('locales'),
            widget_kwargs={
                'attrs': {
                    'data-display-dependency': '#id_send_waitinglist'
                }
            },
            initial=LazyI18nString.from_gettext(
                gettext_noop(
                    'Hello,\n\n'
                    'with this email, we regret to inform you that {event} has been canceled.\n\n'
                    'You will therefore not receive a ticket from the waiting list.\n\n'
                    'Best regards,\n\n'
                    'Your {event} team')))
        self._set_field_placeholders('send_waitinglist_subject',
                                     ['event_or_subevent', 'event'])
        self._set_field_placeholders('send_waitinglist_message',
                                     ['event_or_subevent', 'event'])

        if self.event.has_subevents:
            self.fields['subevent'].queryset = self.event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-inverse-dependency':
                    '#id_all_subevents',
                    'data-model-select2':
                    'event',
                    'data-select2-url':
                    reverse('control:event.subevents.select2',
                            kwargs={
                                'event': self.event.slug,
                                'organizer': self.event.organizer.slug,
                            }),
                    'data-placeholder':
                    pgettext_lazy('subevent', 'All dates')
                })
            self.fields['subevent'].widget.choices = self.fields[
                'subevent'].choices
        else:
            del self.fields['subevent']
            del self.fields['all_subevents']
        change_decimal_field(self.fields['keep_fee_fixed'],
                             self.event.currency)

    def clean(self):
        d = super().clean()
        if d.get('subevent') and d.get('subevents_from'):
            raise ValidationError(
                pgettext_lazy(
                    'subevent',
                    'Please either select a specific date or a date range, not both.'
                ))
        if d.get('all_subevents') and d.get('subevent_from'):
            raise ValidationError(
                pgettext_lazy(
                    'subevent',
                    'Please either select all dates or a date range, not both.'
                ))
        if bool(d.get('subevents_from')) != bool(d.get('subevents_to')):
            raise ValidationError(
                pgettext_lazy(
                    'subevent',
                    'If you set a date range, please set both a start and an end.'
                ))
        if self.event.has_subevents and not d['subevent'] and not d[
                'all_subevents'] and not d.get('subevents_from'):
            raise ValidationError(
                _('Please confirm that you want to cancel ALL dates in this event series.'
                  ))
        return d
예제 #8
0
class TemporalFieldForm(ReprForm):
    _date = forms.DateField()
    _date_time = forms.DateTimeField()
    _duration = forms.DurationField()
    _time = forms.TimeField()
    _split_date_time = forms.SplitDateTimeField()
예제 #9
0
class WhenForm(forms.Form):
    value = forms.DateTimeField(initial=get_utc_now, required=False)
    split_value = forms.SplitDateTimeField(initial=get_utc_now, required=False)
예제 #10
0
파일: forms.py 프로젝트: yephper/django
class EventSplitForm(forms.Form):
    dt = forms.SplitDateTimeField()
예제 #11
0
class ResumeForm(TendenciBaseForm):

    description = forms.CharField(required=False,
                                  widget=TinyMCE(
                                      attrs={'style': 'width:100%'},
                                      mce_attrs={
                                          'storme_app_label':
                                          Resume._meta.app_label,
                                          'storme_model':
                                          Resume._meta.model_name.lower()
                                      }))

    resume_url = forms.CharField(
        label=_('Resume URL'),
        help_text=_("Link to an external resume (eg. Google Docs)"),
        required=False)

    is_agency = forms.BooleanField(
        label=_('Agency'),
        help_text=_("Are you an agency posting this resume?"),
        required=False)

    requested_duration = forms.ChoiceField(
        label=_('Duration'),
        choices=(
            ('30', _('30 Days')),
            ('60', _('60 Days')),
            ('90', _('90 Days')),
        ),
        help_text=_("Amount of days you would like your resume to stay up."),
        required=False)

    captcha = CustomCatpchaField(label=_('Type the code below'))

    contact_email = EmailVerificationField(label=_("Contact email"),
                                           required=False)
    contact_country = CountrySelectField(label=_("Contact country"),
                                         required=False)

    activation_dt = forms.SplitDateTimeField(label=_('Activation Date/Time'),
                                             initial=datetime.now())

    expiration_dt = forms.SplitDateTimeField(label=_('Expriation Date/Time'),
                                             initial=(datetime.now() +
                                                      timedelta(days=30)))

    syndicate = forms.BooleanField(label=_('Include in RSS Feed'),
                                   required=False,
                                   initial=True)

    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('pending', _('Pending')),
    ))

    class Meta:
        model = Resume
        fields = (
            'title',
            'slug',
            'description',
            'resume_url',
            'resume_file',
            'location',
            'skills',
            'experience',
            'awards',
            'education',
            'is_agency',
            'requested_duration',
            'tags',
            'contact_name',
            'contact_address',
            'contact_address2',
            'contact_city',
            'contact_state',
            'contact_zip_code',
            'contact_country',
            'contact_phone',
            'contact_phone2',
            'contact_fax',
            'contact_email',
            'contact_website',
            'captcha',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'activation_dt',
            'expiration_dt',
            'syndicate',
            'status_detail',
        )

        fieldsets = [(_('Resume Information'), {
            'fields': [
                'title',
                'slug',
                'description',
                'resume_url',
                'resume_file',
                'location',
                'skills',
                'experience',
                'awards',
                'education',
                'tags',
                'requested_duration',
                'is_agency',
            ],
            'legend':
            ''
        }),
                     (_('Contact'), {
                         'fields': [
                             'contact_name',
                             'contact_address',
                             'contact_address2',
                             'contact_city',
                             'contact_state',
                             'contact_zip_code',
                             'contact_country',
                             'contact_phone',
                             'contact_phone2',
                             'contact_fax',
                             'contact_email',
                             'contact_website',
                         ],
                         'classes': ['contact'],
                     }),
                     (_('Security Code'), {
                         'fields': [
                             'captcha',
                         ],
                         'classes': ['captcha'],
                     }),
                     (_('Permissions'), {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     (_('Administrator Only'), {
                         'fields': [
                             'activation_dt', 'expiration_dt', 'syndicate',
                             'status', 'status_detail'
                         ],
                         'classes': ['admin-only'],
                     })]

    def __init__(self, *args, **kwargs):
        super(ResumeForm, self).__init__(*args, **kwargs)

        if self.instance.pk:
            self.fields['description'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['description'].widget.mce_attrs['app_instance_id'] = 0

        # adjust fields depending on user status
        fields_to_pop = []
        if not self.user.is_authenticated:
            fields_to_pop += [
                'allow_anonymous_view', 'user_perms', 'member_perms',
                'group_perms', 'activation_dt', 'expiration_dt', 'syndicate',
                'status_detail'
            ]
        else:
            fields_to_pop += ['captcha']
        if not self.user.profile.is_superuser:
            fields_to_pop += [
                'allow_anonymous_view', 'user_perms', 'member_perms',
                'group_perms', 'activation_dt', 'expiration_dt', 'syndicate',
                'status_detail'
            ]
        for f in list(set(fields_to_pop)):
            if f in self.fields: self.fields.pop(f)

    def clean_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False

    def clean_resume_file(self):
        resume = self.cleaned_data['resume_file']
        if resume:
            extension = splitext(resume.name)[1]
            # check the extension
            if extension.lower() not in ALLOWED_FILE_EXT:
                raise forms.ValidationError(
                    _('The file must be of doc, docx, pdf, or rtf format.'))
        return resume

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

        print(self.errors)

        return cleaned_data
예제 #12
0
class EditTimeForm(forms.Form):
    title = forms.CharField(max_length=100)
    createdTime = forms.SplitDateTimeField()
예제 #13
0
class AddForm(forms.Form):
    title = forms.CharField(max_length=100)
    text = forms.CharField()
    createdTime = forms.SplitDateTimeField()
    priority = forms.ChoiceField(choices=PRIORITY_CHOICES)
    finished = forms.ChoiceField(choices=STATUS_CHOICES)
예제 #14
0
파일: forms.py 프로젝트: tbpmig/mig-website
                    _('The event shift must start before '
                      'it can end; use am/pm to specify.')))
        if error_list:
            raise ValidationError(error_list)
        return cleaned_data


EventShiftFormset = inlineformset_factory(
    CalendarEvent,
    EventShift,
    form=EventShiftForm,
    exclude=['drivers', 'attendees', 'google_event_id'],
    extra=1)

valid_time_formats = ['%H:%M', '%I:%M%p', '%X', '%I:%M %p', '%I%p']
EventShiftFormset.form.base_fields['start_time'] = forms.SplitDateTimeField(
    input_time_formats=valid_time_formats)
EventShiftFormset.form.base_fields['start_time'].label = ('Select a start '
                                                          'date and time')
EventShiftFormset.form.base_fields['end_time'] = forms.SplitDateTimeField(
    input_time_formats=valid_time_formats)
EventShiftFormset.form.base_fields['end_time'].label = ('Select an end date '
                                                        'and time')

EventShiftEditFormset = inlineformset_factory(
    CalendarEvent,
    EventShift,
    form=EventShiftForm,
    extra=1,
    exclude=['drivers', 'attendees', 'google_event_id'])
EventShiftEditFormset.form.base_fields['start_time'] =\
    forms.SplitDateTimeField(input_time_formats=valid_time_formats)
예제 #15
0
class CreateReservationForm(forms.Form):
    parking_spot_id = forms.IntegerField(required=True)
    begin = forms.SplitDateTimeField(required=True)
    end = forms.SplitDateTimeField(required=True)
예제 #16
0
class ReservaForm(forms.Form):

    name_validator = RegexValidator(
        regex='^[A-Za-záéíóúñÑÁÉÍÓÚäëïöüÄËÏÖÜ\'\- ]+$',
        message=
        'La entrada debe ser un nombre en Español sin símbolos especiales.')

    ci_validator = RegexValidator(
        regex='^[VE]-[1-9][0-9]{4}[0-9]+$',
        message=
        'Introduzca un CI con un formato válido de la forma V/E-xxxxxxxx.')

    nombre = forms.CharField(required=True,
                             label="Nombre",
                             validators=[name_validator],
                             widget=forms.TextInput(
                                 attrs={
                                     'class': 'form-control',
                                     'placeholder': 'Nombre',
                                     'pattern': name_validator.regex.pattern,
                                     'message': name_validator.message
                                 }))

    apellido = forms.CharField(required=True,
                               label="Apellido",
                               validators=[name_validator],
                               widget=forms.TextInput(
                                   attrs={
                                       'class': 'form-control',
                                       'placeholder': 'Apellido',
                                       'pattern': name_validator.regex.pattern,
                                       'message': name_validator.message
                                   }))

    ci = forms.CharField(required=True,
                         label="Cédula",
                         validators=[ci_validator],
                         widget=forms.TextInput(
                             attrs={
                                 'class': 'form-control',
                                 'placeholder': 'V/E-xxxxxxxx',
                                 'pattern': ci_validator.regex.pattern,
                                 'message': ci_validator.message
                             }))

    inicio = forms.SplitDateTimeField(
        required=True,
        label='Horario Inicio Reserva',
        widget=CustomSplitDateTimeWidget(
            attrs={
                'class': 'form-control',
                'type': 'date',
                'placeholder': 'Hora Inicio Reserva'
            }))

    final = forms.SplitDateTimeField(
        required=True,
        label='Horario Final Reserva',
        widget=CustomSplitDateTimeWidget(
            attrs={
                'class': 'form-control',
                'type': 'date',
                'placeholder': 'Hora Final Reserva'
            }))

    choices_tipoVehiculo = [('Moto', 'Moto'), ('Carro', 'Carro'),
                            ('Camion', 'Camión'),
                            ('Vehículo Especial', 'Vehículo Especial')]

    tipoVehiculo = forms.ChoiceField(
        required=True,
        choices=choices_tipoVehiculo,
        widget=forms.Select(attrs={'class': 'form-control'}))
예제 #17
0
파일: forms.py 프로젝트: iniForum/tendenci
class VideoForm(TendenciBaseForm):
    release_dt = forms.SplitDateTimeField(
        label=_('Release Date/Time'),
        input_date_formats=['%Y-%m-%d', '%m/%d/%Y'],
        input_time_formats=['%I:%M %p', '%H:%M:%S'])
    description = forms.CharField(required=False,
                                  widget=TinyMCE(
                                      attrs={'style': 'width:100%'},
                                      mce_attrs={
                                          'storme_app_label':
                                          Video._meta.app_label,
                                          'storme_model':
                                          Video._meta.model_name.lower()
                                      }))

    status_detail = forms.ChoiceField(choices=(('active', 'Active'),
                                               ('pending', 'Pending')))

    clear_image = forms.BooleanField(required=False)

    class Meta:
        model = Video
        fields = (
            'title',
            'slug',
            'category',
            'video_type',
            'image',
            'video_url',
            'tags',
            'group',
            'description',
            'release_dt',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'member_perms',
            'status_detail',
        )
        fieldsets = (
            (None, {
                'fields': ('title', 'slug', 'category', 'video_type', 'image',
                           'clear_image', 'video_url', 'group', 'tags',
                           'description', 'release_dt')
            }),
            (_('Permissions'), {
                'fields': [
                    'allow_anonymous_view',
                    'user_perms',
                    'member_perms',
                    'group_perms',
                ],
                'classes': ['permissions'],
            }),
            (_('Publishing Status'), {
                'fields': ('status_detail', )
            }),
        )

    def __init__(self, *args, **kwargs):
        super(VideoForm, self).__init__(*args, **kwargs)
        self.embedly_403 = False
        self.fields['group'].queryset = Group.objects.filter(
            status=True, status_detail="active").order_by('name')
        if self.instance.pk:
            self.fields['description'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['description'].widget.mce_attrs['app_instance_id'] = 0
        self.fields['release_dt'].widget = widgets.AdminSplitDateTime()
        self.fields['release_dt'].initial = datetime.now()

    def clean(self, *args, **kwargs):
        super(VideoForm, self).clean(*args, **kwargs)
        if self.embedly_403:
            if not self.cleaned_data.get('image'):
                raise forms.ValidationError(
                    'Please provide a thumbnail of your video in the image upload field.'
                )
        return self.cleaned_data

    def clean_video_url(self):
        video_url = self.cleaned_data.get('video_url')

        if not video_url:
            raise forms.ValidationError('You must enter a URL')

        if self.instance and self.instance.video_url == video_url:
            # the video_url is not changed, let it go
            return video_url

        # Get embedded object from URL
        client = get_embedly_client()
        obj = client.oembed(video_url)
        if obj.get('error'):
            if obj.get('error_code') != 403:
                raise forms.ValidationError(
                    'This url is not supported by embed.ly')
            else:
                # if youbube video, we can get the thumbnail from youtube API
                if 'www.youtube.com' not in video_url:
                    self.embedly_403 = True
        return video_url

    def save(self, *args, **kwargs):
        video = super(VideoForm, self).save(*args, **kwargs)
        if self.cleaned_data['clear_image']:
            video.image.delete()
        return video
예제 #18
0
파일: forms.py 프로젝트: Tusky/tendenci
class ArticleForm(TendenciBaseForm):
    body = forms.CharField(required=False,
                           widget=TinyMCE(attrs={'style': 'width:100%'},
                                          mce_attrs={
                                              'storme_app_label':
                                              Article._meta.app_label,
                                              'storme_model':
                                              Article._meta.model_name.lower()
                                          }))

    release_dt = forms.SplitDateTimeField(
        label=_('Release Date/Time'),
        input_date_formats=['%Y-%m-%d', '%m/%d/%Y'],
        input_time_formats=['%I:%M %p', '%H:%M:%S'])

    contributor_type = forms.ChoiceField(choices=CONTRIBUTOR_CHOICES,
                                         initial=Article.CONTRIBUTOR_AUTHOR,
                                         widget=forms.RadioSelect())
    syndicate = forms.BooleanField(label=_('Include in RSS feed'),
                                   required=False,
                                   initial=True)
    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('pending', _('Pending')),
    ))
    email = EmailVerificationField(label=_("Email"), required=False)
    group = forms.ChoiceField(required=True, choices=[])

    class Meta:
        model = Article
        fields = (
            'headline',
            'slug',
            'summary',
            'body',
            'source',
            'website',
            'release_dt',
            'timezone',
            'contributor_type',
            'first_name',
            'last_name',
            'google_profile',
            'phone',
            'fax',
            'email',
            'group',
            'tags',
            'allow_anonymous_view',
            'syndicate',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [(_('Article Information'), {
            'fields': [
                'headline',
                'slug',
                'summary',
                'body',
                'group',
                'tags',
                'source',
                'website',
                'release_dt',
                'timezone',
            ],
            'legend':
            ''
        }),
                     (_('Contributor'), {
                         'fields': ['contributor_type', 'google_profile'],
                         'classes': ['boxy-grey'],
                     }),
                     (_('Author'), {
                         'fields': [
                             'first_name',
                             'last_name',
                             'phone',
                             'fax',
                             'email',
                         ],
                         'classes': ['contact'],
                     }),
                     (_('Permissions'), {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     (_('Administrator Only'), {
                         'fields': ['syndicate', 'status_detail'],
                         'classes': ['admin-only'],
                     })]

    def __init__(self, *args, **kwargs):
        super(ArticleForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['body'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['group'].initial = Group.objects.get_initial_group_id()
        default_groups = Group.objects.filter(status=True,
                                              status_detail="active")

        if self.user and not self.user.profile.is_superuser:
            if 'status_detail' in self.fields:
                self.fields.pop('status_detail')

            filters = get_query_filters(self.user, 'user_groups.view_group',
                                        **{'perms_field': False})
            groups = default_groups.filter(filters).distinct()
            groups_list = list(groups.values_list('pk', 'name'))

            users_groups = self.user.profile.get_groups()
            for g in users_groups:
                if [g.id, g.name] not in groups_list:
                    groups_list.append([g.id, g.name])
        else:
            groups_list = default_groups.values_list('pk', 'name')

        self.fields['group'].choices = groups_list
        self.fields['google_profile'].help_text = mark_safe(
            GOOGLE_PLUS_HELP_TEXT)
        self.fields['timezone'].initial = settings.TIME_ZONE

        self.fields['release_dt'].initial = datetime.now()

    def clean_group(self):
        group_id = self.cleaned_data['group']

        try:
            group = Group.objects.get(pk=group_id)
            return group
        except Group.DoesNotExist:
            raise forms.ValidationError(_('Invalid group selected.'))

    def clean_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False
예제 #19
0
class EventCreateForm(forms.ModelForm):

    AGE_RANGES = (
        ("0005", "0-5"),
        ("0609", "6-9"),
        ("1012", "10-12"),
        ("1314", "13-14"),
    )

    TYPES = (
        ("1", "Παιδικά θέατρα"),
        ("2", "Συναυλίες"),
        ("3", "Παιδότοποι"),
        ("4", "Πάρτυ"),
        ("5", "Εκπαιδευτικές εκδρομές/εκδηλώσεις"),
        ("6", "Αθλητικές δραστηριότητες"),
        ("7", "Πάρκα αναψυχής"),
        ("8", "Παιδικές κατασκηνώσεις"),
    )

    title = forms.CharField(max_length=50,
                            label='Τίτλος Εκδήλωσης',
                            required=True)
    event_date = forms.SplitDateTimeField(
        help_text='\n Μορφή ημερομηνίας: YYYY-MM-DD, Μορφή ώρας: HH:MM:SS',
        label='Ημερομηνία και ώρα Εκδήλωσης',
        required=True)
    date_added = forms.DateField(help_text='Μορφή ημερομηνίας: YYYY-MM-DD',
                                 initial=datetime.date.today,
                                 label='Ημερομηνία Δημιουργίας Εκδήλωσης',
                                 required=True)
    capacity = forms.IntegerField(min_value=1,
                                  label='Χωρητικότητα Εκδήλωσης',
                                  required=True)
    location = forms.CharField(max_length=100,
                               label='Διεύθυνση Εκδήλωσης',
                               required=True)
    age_range = forms.ChoiceField(choices=AGE_RANGES,
                                  initial="0005",
                                  label='Ηλικιακό Εύρος Εκδήλωσης',
                                  required=True)
    event_type = forms.ChoiceField(choices=TYPES,
                                   initial="1",
                                   label='Είδος Εκδήλωσης',
                                   required=True)
    cost = forms.IntegerField(min_value=0,
                              label='Κόστος Εκδήλωσης (Σε Coins)',
                              required=True)

    class Meta:
        model = User
        fields = [
            'title', 'event_date', 'date_added', 'capacity', 'location',
            'age_range', 'event_type', 'cost'
        ]

    @transaction.atomic
    def save(self, request, lat, lng):
        event = super().save(commit=False)
        event.title = self.cleaned_data['title']
        event.event_date = self.cleaned_data['event_date']
        event.date_added = self.cleaned_data['date_added']
        event.capacity = self.cleaned_data['capacity']
        event.latitude = lat
        event.longitude = lng
        event.location = self.cleaned_data['location']
        event.age_range = self.cleaned_data['age_range']
        event.event_type = self.cleaned_data['event_type']
        event.cost = self.cleaned_data['cost']
        temp = Provider.objects.get(pk=request.user)
        event.hits = 0
        event.availability = self.cleaned_data['capacity']

        event = Event.objects.create(
            location=self.cleaned_data['location'],
            latitude=lat,
            longitude=lng,
            title=self.cleaned_data['title'],
            event_date=self.cleaned_data['event_date'],
            date_added=self.cleaned_data['date_added'],
            capacity=self.cleaned_data['capacity'],
            age_range=self.cleaned_data['age_range'],
            event_type=self.cleaned_data['event_type'],
            cost=self.cleaned_data['cost'],
            hits=0,
            availability=self.cleaned_data['capacity'],
            provider=temp)
        return event
예제 #20
0
class TestForm(forms.Form):
    """Form with a variety of widgets to test bootstrap3 rendering."""

    date = forms.DateField(required=False)
    datetime = forms.SplitDateTimeField(widget=AdminSplitDateTime(),
                                        required=False)
    subject = forms.CharField(
        max_length=100,
        help_text="my_help_text",
        required=True,
        widget=forms.TextInput(attrs={"placeholder": "placeholdertest"}),
    )
    password = forms.CharField(widget=forms.PasswordInput)
    message = forms.CharField(required=False, help_text="<i>my_help_text</i>")
    sender = forms.EmailField(label="Sender © unicode",
                              help_text='E.g., "*****@*****.**"')
    secret = forms.CharField(initial=42, widget=forms.HiddenInput)
    weird = forms.CharField(
        help_text="strings are now utf-8 \u03BCnico\u0394é!")
    cc_myself = forms.BooleanField(
        required=False,
        help_text=
        'cc stands for "carbon copy." You will get a copy in your mailbox.')
    select1 = forms.ChoiceField(choices=RADIO_CHOICES)
    select2 = forms.MultipleChoiceField(choices=RADIO_CHOICES,
                                        help_text="Check as many as you like.")
    select3 = forms.ChoiceField(choices=MEDIA_CHOICES)
    select4 = forms.MultipleChoiceField(choices=MEDIA_CHOICES,
                                        help_text="Check as many as you like.")
    category1 = forms.ChoiceField(choices=RADIO_CHOICES,
                                  widget=forms.RadioSelect)
    category2 = forms.MultipleChoiceField(
        choices=RADIO_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        help_text="Check as many as you like.")
    category3 = forms.ChoiceField(widget=forms.RadioSelect,
                                  choices=MEDIA_CHOICES)
    category4 = forms.MultipleChoiceField(
        choices=MEDIA_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        help_text="Check as many as you like.")
    number = forms.FloatField()
    url = forms.URLField()
    addon = forms.CharField(widget=forms.TextInput(attrs={
        "addon_before": "before",
        "addon_after": "after"
    }))

    # TODO: Re-enable this after Django 1.11 #28105 is available
    # polygon = gisforms.PointField()

    required_css_class = "bootstrap3-req"

    # Set this to allow tests to work properly in Django 1.10+
    # More information, see issue #337
    use_required_attribute = False

    def clean(self):
        cleaned_data = super().clean()
        raise forms.ValidationError(
            "This error was added to show the non field errors styling.")
        return cleaned_data
예제 #21
0
파일: admin.py 프로젝트: dtcooper/tomato
class GenerateStopSetForm(forms.Form):
    now = forms.SplitDateTimeField(widget=AdminSplitDateTime(), required=False)
예제 #22
0
파일: forms.py 프로젝트: astrocbxy/pretix
class MailForm(FormPlaceholderMixin, forms.Form):
    recipients = forms.ChoiceField(label=_('Send email to'),
                                   widget=forms.RadioSelect,
                                   initial='orders',
                                   choices=[])
    sendto = forms.MultipleChoiceField()  # overridden later
    subject = forms.CharField(label=_("Subject"))
    message = forms.CharField(label=_("Message"))
    attachment = CachedFileField(
        label=_("Attachment"),
        required=False,
        ext_whitelist=(".png", ".jpg", ".gif", ".jpeg", ".pdf", ".txt",
                       ".docx", ".gif", ".svg", ".pptx", ".ppt", ".doc",
                       ".xlsx", ".xls", ".jfif", ".heic", ".heif", ".pages",
                       ".bmp", ".tif", ".tiff"),
        help_text=_(
            'Sending an attachment increases the chance of your email not arriving or being sorted into spam folders. We recommend only using PDFs '
            'of no more than 2 MB in size.'),
        max_size=10 * 1024 * 1024)  # TODO i18n
    items = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple(
            attrs={'class': 'scrolling-multiple-choice'}),
        label=_('Only send to people who bought'),
        required=True,
        queryset=Item.objects.none())
    filter_checkins = forms.BooleanField(label=_('Filter check-in status'),
                                         required=False)
    checkin_lists = SafeModelMultipleChoiceField(
        queryset=CheckinList.objects.none(),
        required=False)  # overridden later
    not_checked_in = forms.BooleanField(
        label=_("Send to customers not checked in"), required=False)
    subevent = forms.ModelChoiceField(SubEvent.objects.none(),
                                      label=_('Only send to customers of'),
                                      required=False,
                                      empty_label=pgettext_lazy(
                                          'subevent', 'All dates'))
    subevents_from = forms.SplitDateTimeField(
        widget=SplitDateTimePickerWidget(),
        label=pgettext_lazy(
            'subevent',
            'Only send to customers of dates starting at or after'),
        required=False,
    )
    subevents_to = forms.SplitDateTimeField(
        widget=SplitDateTimePickerWidget(),
        label=pgettext_lazy('subevent',
                            'Only send to customers of dates starting before'),
        required=False,
    )
    created_from = forms.SplitDateTimeField(
        widget=SplitDateTimePickerWidget(),
        label=pgettext_lazy(
            'subevent', 'Only send to customers with orders created after'),
        required=False,
    )
    created_to = forms.SplitDateTimeField(
        widget=SplitDateTimePickerWidget(),
        label=pgettext_lazy(
            'subevent', 'Only send to customers with orders created before'),
        required=False,
    )

    def clean(self):
        d = super().clean()
        if d.get('subevent') and (d.get('subevents_from')
                                  or d.get('subevents_to')):
            raise ValidationError(
                pgettext_lazy(
                    'subevent',
                    'Please either select a specific date or a date range, not both.'
                ))
        if bool(d.get('subevents_from')) != bool(d.get('subevents_to')):
            raise ValidationError(
                pgettext_lazy(
                    'subevent',
                    'If you set a date range, please set both a start and an end.'
                ))
        return d

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

        recp_choices = [('orders', _('Everyone who created a ticket order'))]
        if event.settings.attendee_emails_asked:
            recp_choices += [
                ('attendees',
                 _('Every attendee (falling back to the order contact when no attendee email address is '
                   'given)')),
                ('both',
                 _('Both (all order contact addresses and all attendee email addresses)'
                   ))
            ]
        self.fields['recipients'].choices = recp_choices

        self.fields['subject'] = I18nFormField(
            label=_('Subject'),
            widget=I18nTextInput,
            required=True,
            locales=event.settings.get('locales'),
        )
        self.fields['message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea,
            required=True,
            locales=event.settings.get('locales'),
        )
        self._set_field_placeholders('subject',
                                     ['event', 'order', 'position_or_address'])
        self._set_field_placeholders('message',
                                     ['event', 'order', 'position_or_address'])
        choices = [(e, l) for e, l in Order.STATUS_CHOICE if e != 'n']
        choices.insert(0, ('na', _('payment pending (except unapproved)')))
        choices.insert(0, ('pa', _('approval pending')))
        if not event.settings.get('payment_term_expire_automatically',
                                  as_type=bool):
            choices.append(('overdue', _('pending with payment overdue')))
        self.fields['sendto'] = forms.MultipleChoiceField(
            label=_("Send to customers with order status"),
            widget=forms.CheckboxSelectMultiple(
                attrs={'class': 'scrolling-multiple-choice no-search'}),
            choices=choices)
        if not self.initial.get('sendto'):
            self.initial['sendto'] = ['p', 'na']
        elif 'n' in self.initial['sendto']:
            self.initial['sendto'].append('pa')
            self.initial['sendto'].append('na')

        self.fields['items'].queryset = event.items.all()
        if not self.initial.get('items'):
            self.initial['items'] = event.items.all()

        self.fields['checkin_lists'].queryset = event.checkin_lists.all()
        self.fields['checkin_lists'].widget = Select2Multiple(
            attrs={
                'data-model-select2':
                'generic',
                'data-select2-url':
                reverse('control:event.orders.checkinlists.select2',
                        kwargs={
                            'event': event.slug,
                            'organizer': event.organizer.slug,
                        }),
                'data-placeholder':
                _('Send to customers checked in on list'),
            })
        self.fields['checkin_lists'].widget.choices = self.fields[
            'checkin_lists'].choices
        self.fields['checkin_lists'].label = _(
            'Send to customers checked in on list')

        if event.has_subevents:
            self.fields['subevent'].queryset = event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-model-select2':
                    'event',
                    'data-select2-url':
                    reverse('control:event.subevents.select2',
                            kwargs={
                                'event': event.slug,
                                'organizer': event.organizer.slug,
                            }),
                    'data-placeholder':
                    pgettext_lazy('subevent', 'Date')
                })
            self.fields['subevent'].widget.choices = self.fields[
                'subevent'].choices
        else:
            del self.fields['subevent']
            del self.fields['subevents_from']
            del self.fields['subevents_to']
class SampleFormWithMultiValueField(forms.Form):
    multi = forms.SplitDateTimeField()
예제 #24
0
class JobForm(TendenciBaseForm):

    description = forms.CharField(required=False,
                                  widget=TinyMCE(
                                      attrs={'style': 'width:100%'},
                                      mce_attrs={
                                          'storme_app_label':
                                          Job._meta.app_label,
                                          'storme_model':
                                          Job._meta.model_name.lower()
                                      }))

    captcha = CustomCatpchaField(label=_('Type the code below'))

    start_dt = forms.SplitDateTimeField(required=False,
                                        label=_('Position starts on:'),
                                        initial=datetime.now())

    activation_dt = forms.SplitDateTimeField(label=_('Activation Date/Time'),
                                             initial=datetime.now())

    post_dt = forms.SplitDateTimeField(label=_('Post Date/Time'),
                                       initial=datetime.now())

    expiration_dt = forms.SplitDateTimeField(label=_('Expiration Date/Time'),
                                             initial=datetime.now())

    syndicate = forms.BooleanField(label=_('Include in RSS Feed'),
                                   required=False,
                                   initial=True)

    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('pending', _('Pending')),
    ))

    list_type = forms.ChoiceField(initial='regular',
                                  choices=(
                                      ('regular', _('Regular')),
                                      ('premium', _('Premium')),
                                  ))
    payment_method = forms.ChoiceField(
        error_messages={'required': _('Please select a payment method.')})

    contact_email = EmailVerificationField(label=_("Contact email"),
                                           required=False)
    contact_country = CountrySelectField(label=_("Contact country"),
                                         required=False)

    group = forms.ModelChoiceField(queryset=Group.objects.filter(
        status=True, status_detail="active"),
                                   required=True,
                                   empty_label=None)

    pricing = forms.ModelChoiceField(
        queryset=JobPricing.objects.filter(status=True).order_by('duration'),
        **request_duration_defaults)
    cat = forms.ModelChoiceField(
        label=_("Category"),
        queryset=JobCategory.objects.filter(parent=None),
        empty_label="-----------",
        required=False)
    sub_cat = forms.ModelChoiceField(
        label=_("Subcategory"),
        queryset=JobCategory.objects.none(),
        empty_label=_("Please choose a category first"),
        required=False)

    class Meta:
        model = Job
        fields = ('title', 'slug', 'description', 'group', 'code', 'location',
                  'skills', 'experience', 'education', 'level', 'period',
                  'is_agency', 'contact_method', 'position_reports_to',
                  'salary_from', 'salary_to', 'computer_skills', 'tags',
                  'pricing', 'list_type', 'start_dt', 'activation_dt',
                  'post_dt', 'expiration_dt', 'job_url', 'entity',
                  'contact_company', 'contact_name', 'contact_address',
                  'contact_address2', 'contact_city', 'contact_state',
                  'contact_zip_code', 'contact_country', 'contact_phone',
                  'contact_fax', 'contact_email', 'contact_website', 'tags',
                  'allow_anonymous_view', 'syndicate', 'status_detail',
                  'payment_method', 'cat', 'sub_cat')

        fieldsets = [
            (_('Job Information'), {
                'fields': [
                    'title', 'slug', 'description', 'group', 'job_url',
                    'start_dt', 'code', 'location', 'skills',
                    'computer_skills', 'experience', 'education', 'level',
                    'period', 'contact_method', 'position_reports_to',
                    'salary_from', 'salary_to', 'is_agency', 'tags', 'pricing',
                    'activation_dt', 'expiration_dt', 'post_dt', 'entity'
                ],
                'legend':
                ''
            }),
            (_('Payment'), {
                'fields': ['list_type', 'payment_method'],
                'classes': ['payment_method'],
            }),
            (_('Contact'), {
                'fields': [
                    'contact_company', 'contact_name', 'contact_address',
                    'contact_address2', 'contact_city', 'contact_state',
                    'contact_zip_code', 'contact_country', 'contact_phone',
                    'contact_fax', 'contact_email', 'contact_website'
                ],
                'classes': ['contact'],
            }),
            (_('Security Code'), {
                'fields': ['captcha'],
                'classes': ['captcha'],
            }),
            (_('Permissions'), {
                'fields': [
                    'allow_anonymous_view',
                    'user_perms',
                    'member_perms',
                    'group_perms',
                ],
                'classes': ['permissions'],
            }),
            (_('Category'), {
                'fields': ['cat', 'sub_cat'],
                'classes': ['boxy-grey job-category'],
            }),
            (_('Administrator Only'), {
                'fields': ['syndicate', 'status_detail'],
                'classes': ['admin-only'],
            })
        ]

    def __init__(self, *args, **kwargs):
        if hasattr(self, 'user'):
            kwargs.update({'user': self.user})
        super(JobForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['description'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
            #self.fields['pricing'].initial = JobPricing.objects.filter(duration=self.instance.requested_duration)[0]
            if self.user.profile.is_superuser:
                self.fields['status_detail'].choices = STATUS_DETAIL_CHOICES
        else:
            self.fields['description'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['group'].initial = Group.objects.get_initial_group_id()

        # cat and sub_cat
        if self.user.profile.is_superuser:
            self.fields['sub_cat'].help_text = mark_safe(
                '<a href="{0}">{1}</a>'.format(
                    reverse('admin:jobs_category_changelist'),
                    _('Manage Categories'),
                ))
        if self.instance and self.instance.pk:
            self.fields['sub_cat'].queryset = JobCategory.objects.filter(
                parent=self.instance.cat)
        if args:
            post_data = args[0]
        else:
            post_data = None
        if post_data:
            cat = post_data.get('cat', '0')
            if cat and cat != '0' and cat != u'':
                cat = JobCategory.objects.get(pk=int(cat))
                self.fields['sub_cat'].queryset = JobCategory.objects.filter(
                    parent=cat)

        self.fields['pricing'].choices = pricing_choices(self.user)

        if 'payment_method' in self.fields:
            choices = get_payment_method_choices(self.user)
            self.fields['payment_method'].widget = forms.RadioSelect(
                choices=choices)
            self.fields['payment_method'].choices = choices
            #self.fields['payment_method'].widget = forms.RadioSelect(choices=choices)
            if choices and len(choices) == 1:
                self.fields['payment_method'].initial = choices[0][0]

        # adjust fields depending on user status
        fields_to_pop = []
        if not self.user.is_authenticated:
            fields_to_pop += [
                'entity', 'allow_anonymous_view', 'user_perms', 'group_perms',
                'member_perms', 'post_dt', 'activation_dt', 'expiration_dt',
                'syndicate', 'status_detail'
            ]
        else:
            fields_to_pop += ['captcha']

        if not self.user.profile.is_superuser:
            fields_to_pop += [
                'slug', 'entity', 'group', 'allow_anonymous_view',
                'user_perms', 'member_perms', 'group_perms', 'post_dt',
                'activation_dt', 'expiration_dt', 'syndicate', 'status_detail'
            ]

        for f in list(set(fields_to_pop)):
            if f in self.fields:
                self.fields.pop(f)

    def clean_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False

    def save(self, *args, **kwargs):
        """
        Assigns the requested_duration of a job based on the
        chosen pricing.
        """
        job = super(JobForm, self).save(commit=False)
        if 'pricing' in self.cleaned_data:
            job.requested_duration = self.cleaned_data['pricing'].duration
        if kwargs['commit']:
            job.save()
        return job
예제 #25
0
class TracheostomyForm(ModelForm):

    pt_id = forms.IntegerField(
        min_value=99999,
        max_value=999999,
        error_messages={
            'min_value': 'Please enter a valid UHID',
            'max_value': 'Please enter a valid UHID'
        },
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'UHID eg: 182029'
        }),
        label='Patient UHID')
    pt_name = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Eg: Ajay Philip'
        }),
        label='Patient Name')
    pt_location = forms.ModelChoiceField(
        queryset=Locations.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Location',
        empty_label=('Unselected'))
    pt_gender = forms.CharField(max_length=50,
                                widget=forms.Select(
                                    choices=ReturnToICU.CHOICES,
                                    attrs={'class': 'form-control'}),
                                label='Patient Gender')
    pt_age = forms.IntegerField(
        min_value=0,
        max_value=200,
        error_messages={
            'min_value': 'Please enter a valid UHID',
            'max_value': 'Please enter a valid UHID'
        },
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'EG: 60'
        }),
        label='Patient Age')
    pt_doctor = forms.ModelChoiceField(
        queryset=Doctors.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Doctor',
        empty_label=('Unselected'))
    pt_diagnosis = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='Diagnosis')

    pt_department = forms.ModelChoiceField(
        queryset=Departments.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Department',
        empty_label=('Unselected'))

    dateofadmission = forms.DateField(widget=AdminDateWidget(),
                                      label="Date of Admission")

    loc_tracheostory = forms.ModelChoiceField(
        queryset=Locations.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Tracheostomy done from:',
        empty_label=('Unselected'))

    datetime_tracheostomy = forms.SplitDateTimeField(
        widget=CustomAdminSplitDateTime(),
        label='Date and Time of Tracheostomy')
    comments = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={'class': 'form-control'}),
        label='Comments')

    report_by = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Nurse Name'
        }),
        label='Report By')

    class Meta:
        model = Tracheostomy
        fields = [
            'pt_id', 'pt_name', 'pt_location', 'pt_gender', 'pt_age',
            'pt_doctor', 'pt_diagnosis', 'pt_department', 'dateofadmission',
            'loc_tracheostory', 'datetime_tracheostomy', 'comments',
            'report_by'
        ]

        exclude = ['timestamp']
예제 #26
0
class DiscountForm(TendenciBaseForm):

    value = PriceField(
        label=_('Discount Value'),
        max_digits=10,
        decimal_places=2,
        help_text=_('Enter discount value as a positive number.'))

    class Meta:
        model = Discount
        fields = (
            'discount_code',
            'value',
            'start_dt',
            'end_dt',
            'never_expires',
            'cap',
            'apps',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [(_('Discount Information'), {
            'fields': [
                'discount_code',
                'value',
                'cap',
                'never_expires',
                'apps',
                'start_dt',
                'end_dt',
            ],
            'legend':
            ''
        }),
                     (_('Permissions'), {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     (_('Administrator Only'), {
                         'fields': ['status_detail'],
                         'classes': ['admin-only'],
                     })]

    start_dt = forms.SplitDateTimeField(label=_('Start Date/Time'),
                                        initial=datetime.now())
    end_dt = forms.SplitDateTimeField(label=_('End Date/Time'),
                                      initial=END_DT_INITIAL)
    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('pending', _('Pending')),
    ))

    def __init__(self, *args, **kwargs):
        super(DiscountForm, self).__init__(*args, **kwargs)
        if self.user and not self.user.profile.is_superuser:
            if 'status_detail' in self.fields: self.fields.pop('status_detail')

        MODELS_WITH_DISCOUNT = ['registrationconfiguration', 'membershipset']
        content_types = ContentType.objects.filter(
            model__in=MODELS_WITH_DISCOUNT)
        if 'apps' in self.fields:
            self.fields['apps'].choices = ((c.id, c.app_label)
                                           for c in content_types)

    def clean_discount_code(self):
        data = self.cleaned_data['discount_code']
        try:
            discount = Discount.objects.get(discount_code=data)
        except Discount.DoesNotExist:
            return data
        if not discount == self.instance:
            raise forms.ValidationError(
                _('There a discount for this code already exists.'))
        return data

    def clean(self):
        cleaned_data = super(DiscountForm, self).clean()
        start_dt = cleaned_data.get("start_dt")
        end_dt = cleaned_data.get("end_dt")

        if start_dt and end_dt:
            if start_dt > end_dt:
                errors = self._errors.setdefault("end_dt", ErrorList())
                errors.append(
                    _(u"This cannot be earlier than the start date."))

        # Always return the full collection of cleaned data.
        return cleaned_data
예제 #27
0
class ReturnToICUForm(ModelForm):

    pt_id = forms.IntegerField(
        min_value=99999,
        max_value=999999,
        error_messages={
            'min_value': 'Please enter a valid UHID',
            'max_value': 'Please enter a valid UHID'
        },
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'UHID eg: 182029'
        }),
        label='Patient UHID')
    pt_age = forms.IntegerField(
        min_value=0,
        max_value=200,
        error_messages={
            'min_value': 'Please enter a valid UHID',
            'max_value': 'Please enter a valid UHID'
        },
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'EG: 60'
        }),
        label='Patient Age')

    pt_department = forms.ModelChoiceField(
        queryset=Departments.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Department',
        empty_label=('Unselected'))
    pt_doctor = forms.ModelChoiceField(
        queryset=Doctors.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Doctor',
        empty_label=('Unselected'))
    pt_location = forms.ModelChoiceField(
        queryset=Locations.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Location',
        empty_label=('Unselected'))
    transfer_to = forms.ModelChoiceField(
        queryset=Locations.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='Transfer To Ward:',
        empty_label=('Unselected'))

    #  datetime_transfer_out = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class':'dateinput form-control hasDatepicker'}))
    datetime_transfer_out = forms.SplitDateTimeField(
        widget=CustomAdminSplitDateTime(),
        label='Date and time of Transfer out')
    datetime_return = forms.SplitDateTimeField(
        widget=CustomAdminSplitDateTime(), label='Date and Time of Return ')

    class Meta:
        model = ReturnToICU
        fields = [
            'pt_id', 'pt_name', 'pt_location', 'pt_gender', 'pt_age',
            'pt_doctor', 'pt_diagnosis', 'pt_department', 'dateofadmission',
            'datetime_transfer_out', 'transfer_to', 'datetime_return',
            'reason_return', 'report_by'
        ]
        widgets = {
            'pt_id':
            forms.NumberInput(attrs={
                'class': 'form-control',
                'placeholder': 'UHID eg: 182029'
            }),
            'pt_name':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Eg: Joy Mathew'
            }),
            'pt_location':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Eg: Joy Mathew'
            }),
            'pt_gender':
            forms.Select(choices=ReturnToICU.CHOICES,
                         attrs={'class': 'form-control'}),
            'pt_age':
            forms.NumberInput(attrs={
                'class': 'form-control',
                'placeholder': "Patient's age"
            }),
            'pt_doctor':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Eg: Dr John'
            }),
            'pt_diagnosis':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Eg: CAD'
            }),
            'pt_department':
            forms.Select(attrs={'class': 'form-control'}),
            'dateofadmission':
            AdminDateWidget(),
            'datetime_transfer_out':
            CustomAdminSplitDateTime(),
            'transfer_to':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Eg: Joy Mathew'
            }),
            'datetime_return':
            forms.TextInput(attrs={'class': 'form-control'}),
            'reason_return':
            forms.Textarea(attrs={
                'class': 'form-control',
                'placeholder': 'Eg:Pt condition worsen'
            }),
            'report_by':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': "Nurse's Name"
            })
        }
        exclude = ['timestamp']

        labels = {
            'pt_id': 'Patient UHID',
            'pt_name': 'Patient Name',
            'pt_location': 'Patient Location',
            'pt_gender': 'Patient Gender',
            'pt_age': 'Patient Age',
            'pt_department': 'Department',
            'pt_diagnosis': 'Diagnosis of Patient',
            'dateofadmission': 'Date of Admission',
            'datetime_transfer_out': 'Date and Time of Transfer out',
            'transfer_to': 'Transfer To Ward:',
            'datetime_return': 'Date and Time of Return:',
            'report_by': 'Report By'
        }
예제 #28
0
파일: tests.py 프로젝트: SpivEgin/devenv
class TestForm(forms.Form):
    """
    Form with a variety of widgets to test bootstrap3 rendering.
    """
    date = forms.DateField(required=False)
    datetime = forms.SplitDateTimeField(widget=AdminSplitDateTime(), required=False)
    subject = forms.CharField(
        max_length=100,
        help_text='my_help_text',
        required=True,
        widget=forms.TextInput(attrs={'placeholder': 'placeholdertest'}),
    )
    password = forms.CharField(widget=forms.PasswordInput)
    message = forms.CharField(required=False, help_text='<i>my_help_text</i>')
    sender = forms.EmailField(
        label='Sender © unicode',
        help_text='E.g., "*****@*****.**"')
    secret = forms.CharField(initial=42, widget=forms.HiddenInput)
    cc_myself = forms.BooleanField(
        required=False,
        help_text='cc stands for "carbon copy." You will get a copy in your mailbox.'
    )
    select1 = forms.ChoiceField(choices=RADIO_CHOICES)
    select2 = forms.MultipleChoiceField(
        choices=RADIO_CHOICES,
        help_text='Check as many as you like.',
    )
    select3 = forms.ChoiceField(choices=MEDIA_CHOICES)
    select4 = forms.MultipleChoiceField(
        choices=MEDIA_CHOICES,
        help_text='Check as many as you like.',
    )
    category1 = forms.ChoiceField(
        choices=RADIO_CHOICES, widget=forms.RadioSelect)
    category2 = forms.MultipleChoiceField(
        choices=RADIO_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        help_text='Check as many as you like.',
    )
    category3 = forms.ChoiceField(
        widget=forms.RadioSelect, choices=MEDIA_CHOICES)
    category4 = forms.MultipleChoiceField(
        choices=MEDIA_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        help_text='Check as many as you like.',
    )
    addon = forms.CharField(
        widget=forms.TextInput(attrs={'addon_before': 'before', 'addon_after': 'after'}),
    )
    polygon = gisforms.PointField()

    required_css_class = 'bootstrap3-req'

    # Set this to allow tests to work properly in Django 1.10+
    # More information, see issue #337
    use_required_attribute = False

    def clean(self):
        cleaned_data = super(TestForm, self).clean()
        raise forms.ValidationError(
            "This error was added to show the non field errors styling.")
        return cleaned_data
예제 #29
0
파일: admin.py 프로젝트: vikas1885/test1
class CourseModeForm(forms.ModelForm):
    class Meta(object):  # pylint: disable=missing-docstring
        model = CourseMode

    COURSE_MODE_SLUG_CHOICES = (
        [(CourseMode.DEFAULT_MODE_SLUG, CourseMode.DEFAULT_MODE_SLUG)] +
        [(mode_slug, mode_slug) for mode_slug in CourseMode.VERIFIED_MODES] +
        [(CourseMode.NO_ID_PROFESSIONAL_MODE,
          CourseMode.NO_ID_PROFESSIONAL_MODE)] +
        [(mode_slug, mode_slug) for mode_slug in CourseMode.CREDIT_MODES])

    mode_slug = forms.ChoiceField(choices=COURSE_MODE_SLUG_CHOICES,
                                  label=_("Mode"))

    # The verification deadline is stored outside the course mode in the verify_student app.
    # (we used to use the course mode expiration_datetime as both an upgrade and verification deadline).
    # In order to make this transition easier, we include the verification deadline as a custom field
    # in the course mode admin form.  Longer term, we will deprecate the course mode Django admin
    # form in favor of an external Course Administration Tool.
    verification_deadline = forms.SplitDateTimeField(
        label=_("Verification Deadline"),
        required=False,
        help_text=_(
            "OPTIONAL: After this date/time, users will no longer be able to submit photos for verification.  "
            "This appies ONLY to modes that require verification."),
        widget=admin.widgets.AdminSplitDateTime,
    )

    def __init__(self, *args, **kwargs):
        super(CourseModeForm, self).__init__(*args, **kwargs)

        default_tz = timezone(settings.TIME_ZONE)

        if self.instance.expiration_datetime:
            # django admin is using default timezone. To avoid time conversion from db to form
            # convert the UTC object to naive and then localize with default timezone.
            expiration_datetime = self.instance.expiration_datetime.replace(
                tzinfo=None)
            self.initial["expiration_datetime"] = default_tz.localize(
                expiration_datetime)

        # Load the verification deadline
        # Since this is stored on a model in verify student, we need to load it from there.
        # We need to munge the timezone a bit to get Django admin to display it without converting
        # it to the user's timezone.  We'll make sure we write it back to the database with the timezone
        # set to UTC later.
        if self.instance.course_id and self.instance.mode_slug in CourseMode.VERIFIED_MODES:
            deadline = verification_models.VerificationDeadline.deadline_for_course(
                self.instance.course_id)
            self.initial["verification_deadline"] = (default_tz.localize(
                deadline.replace(
                    tzinfo=None)) if deadline is not None else None)

    def clean_course_id(self):
        course_id = self.cleaned_data['course_id']
        try:
            course_key = CourseKey.from_string(course_id)
        except InvalidKeyError:
            try:
                course_key = SlashSeparatedCourseKey.from_deprecated_string(
                    course_id)
            except InvalidKeyError:
                raise forms.ValidationError(
                    "Cannot make a valid CourseKey from id {}!".format(
                        course_id))

        if not modulestore().has_course(course_key):
            raise forms.ValidationError(
                "Cannot find course with id {} in the modulestore".format(
                    course_id))

        return course_key

    def clean_expiration_datetime(self):
        """
        Ensure that the expiration datetime we save uses the UTC timezone.
        """
        # django admin saving the date with default timezone to avoid time conversion from form to db
        # changes its tzinfo to UTC
        if self.cleaned_data.get("expiration_datetime"):
            return self.cleaned_data.get("expiration_datetime").replace(
                tzinfo=UTC)

    def clean_verification_deadline(self):
        """
        Ensure that the verification deadline we save uses the UTC timezone.
        """
        if self.cleaned_data.get("verification_deadline"):
            return self.cleaned_data.get("verification_deadline").replace(
                tzinfo=UTC)

    def clean(self):
        """
        Clean the form fields.
        This is the place to perform checks that involve multiple form fields.
        """
        cleaned_data = super(CourseModeForm, self).clean()
        mode_slug = cleaned_data.get("mode_slug")
        upgrade_deadline = cleaned_data.get("expiration_datetime")
        verification_deadline = cleaned_data.get("verification_deadline")

        # Allow upgrade deadlines ONLY for the "verified" mode
        # This avoids a nasty error condition in which the upgrade deadline is set
        # for a professional education course before the enrollment end date.
        # When this happens, the course mode expires and students are able to enroll
        # in the course for free.  To avoid this, we explicitly prevent admins from
        # setting an upgrade deadline for any mode except "verified" (which has an upgrade path).
        if upgrade_deadline is not None and mode_slug != CourseMode.VERIFIED:
            raise forms.ValidationError(
                'Only the "verified" mode can have an upgrade deadline.  '
                'For other modes, please set the enrollment end date in Studio.'
            )

        # Verification deadlines are allowed only for verified modes
        if verification_deadline is not None and mode_slug not in CourseMode.VERIFIED_MODES:
            raise forms.ValidationError(
                "Verification deadline can be set only for verified modes.")

        # Verification deadline must be after the upgrade deadline,
        # if an upgrade deadline is set.
        # There are cases in which we might want to set a verification deadline,
        # but not an upgrade deadline (for example, a professional education course that requires verification).
        if verification_deadline is not None:
            if upgrade_deadline is not None and verification_deadline < upgrade_deadline:
                raise forms.ValidationError(
                    "Verification deadline must be after the upgrade deadline."
                )

        return cleaned_data

    def save(self, commit=True):
        """
        Save the form data.
        """
        # Trigger validation so we can access cleaned data
        if self.is_valid():
            course_key = self.cleaned_data.get("course_id")
            verification_deadline = self.cleaned_data.get(
                "verification_deadline")
            mode_slug = self.cleaned_data.get("mode_slug")

            # Since the verification deadline is stored in a separate model,
            # we need to handle saving this ourselves.
            # Note that verification deadline can be `None` here if
            # the deadline is being disabled.
            if course_key is not None and mode_slug in CourseMode.VERIFIED_MODES:
                verification_models.VerificationDeadline.set_deadline(
                    course_key, verification_deadline)

        return super(CourseModeForm, self).save(commit=commit)
예제 #30
0
class DirectoryForm(TendenciBaseForm):
    body = forms.CharField(label=_("Description"), required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Directory._meta.app_label,
        'storme_model':Directory._meta.model_name.lower()}))

    logo = forms.FileField(
      required=False,
      help_text=_('Company logo. Only jpg, gif, or png images.'))

    syndicate = forms.BooleanField(label=_('Include in RSS Feed'), required=False, initial=True)

    status_detail = forms.ChoiceField(
        choices=(('active',_('Active')),('inactive',_('Inactive')), ('pending',_('Pending')),))

    list_type = forms.ChoiceField(initial='regular', choices=(('regular',_('Regular')),
                                                              ('premium', _('Premium')),))
    payment_method = forms.CharField(error_messages={'required': _('Please select a payment method.')})

    activation_dt = forms.SplitDateTimeField(initial=datetime.now())
    expiration_dt = forms.SplitDateTimeField(initial=datetime.now())

    email = EmailVerificationField(label=_("Email"), required=False)
    email2 = EmailVerificationField(label=_("Email 2"), required=False)
    country = CountrySelectField(label=_("Country"), required=False)

    pricing = forms.ModelChoiceField(queryset=DirectoryPricing.objects.filter(status=True).order_by('duration'),
                    **request_duration_defaults)

    cat = forms.ModelChoiceField(label=_("Category"),
                                      queryset=DirectoryCategory.objects.filter(parent=None),
                                      empty_label="-----------",
                                      required=False)
    sub_cat = forms.ModelChoiceField(label=_("Subcategory"),
                                          queryset=DirectoryCategory.objects.none(),
                                          empty_label=_("Please choose a category first"),
                                          required=False)

    class Meta:
        model = Directory
        fields = (
            'headline',
            'slug',
            'summary',
            'body',
            'logo',
            'source',
            'timezone',
            'first_name',
            'last_name',
            'address',
            'address2',
            'city',
            'state',
            'zip_code',
            'country',
            'phone',
            'phone2',
            'fax',
            'email',
            'email2',
            'website',
            'linkedin',
            'facebook',
            'twitter',
            'instagram',
            'youtube',
            'tags',
            'pricing',
            'list_type',
            'payment_method',
            'activation_dt',
            'expiration_dt',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_user_edit',
            'syndicate',
            'user_perms',
            'member_perms',
            'group_perms',
            'cat',
            'sub_cat',
            'status_detail',
        )

        fieldsets = [(_('Directory Information'), {
                      'fields': ['headline',
                                 'slug',
                                 'summary',
                                 'body',
                                 'logo',
                                 'tags',
                                 'source',
                                 'timezone',
                                 'activation_dt',
                                 'pricing',
                                 'expiration_dt',
                                 ],
                      'legend': ''
                      }),
                      (_('Payment'), {
                      'fields': ['list_type',
                                 'payment_method'
                                 ],
                        'classes': ['payment_method'],
                      }),
                      (_('Contact'), {
                      'fields': ['first_name',
                                 'last_name',
                                  'address',
                                  'address2',
                                  'city',
                                  'state',
                                  'zip_code',
                                  'country',
                                  'phone',
                                  'phone2',
                                  'fax',
                                  'email',
                                  'email2',
                                  'website'
                                 ],
                        'classes': ['contact'],
                      }),
                     (_('Social Media'), {
                      'fields': ['linkedin',
                                 'facebook',
                                  'twitter',
                                  'instagram',
                                  'youtube',
                                 ],
                        'classes': ['social-media'],
                      }),
                      (_('Permissions'), {
                      'fields': ['allow_anonymous_view',
                                 'user_perms',
                                 'member_perms',
                                 'group_perms',
                                 ],
                      'classes': ['permissions'],
                      }),
                      (_('Category'), {
                        'fields': ['cat',
                                   'sub_cat'
                                   ],
                        'classes': ['boxy-grey job-category'],
                      }),
                     (_('Administrator Only'), {
                      'fields': ['syndicate',
                                 'status_detail'],
                      'classes': ['admin-only'],
                    })]

    def __init__(self, *args, **kwargs):
        super(DirectoryForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            if self.user.profile.is_superuser:
                self.fields['status_detail'].choices = (('active',_('Active')),
                                                        ('inactive',_('Inactive')),
                                                        ('pending',_('Pending')),
                                                        ('paid - pending approval', _('Paid - Pending Approval')),)
        else:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = 0

        if self.instance.logo:
            self.initial['logo'] = self.instance.logo

        if not self.user.profile.is_superuser:
            if 'status_detail' in self.fields: self.fields.pop('status_detail')

        if 'payment_method' in self.fields:
            self.fields['payment_method'] = forms.ChoiceField(widget=forms.RadioSelect, choices=get_payment_method_choices(self.user))
        if 'pricing' in self.fields:
            self.fields['pricing'].choices = get_duration_choices(self.user)

        self.fields['timezone'].initial = settings.TIME_ZONE

        # cat and sub_cat
        if self.user.profile.is_superuser:
            self.fields['sub_cat'].help_text = mark_safe('<a href="{0}">{1}</a>'.format(
                                        reverse('admin:directories_category_changelist'),
                                        _('Manage Categories'),))
        if self.instance and self.instance.pk:
            self.fields['sub_cat'].queryset = DirectoryCategory.objects.filter(
                                                        parent=self.instance.cat)
        if args:
            post_data = args[0]
        else:
            post_data = None
        if post_data:
            cat = post_data.get('cat', '0')
            if cat and cat != '0' and cat != u'':
                cat = DirectoryCategory.objects.get(pk=int(cat))
                self.fields['sub_cat'].queryset = DirectoryCategory.objects.filter(parent=cat)

        # expiration_dt = activation_dt + requested_duration
        fields_to_pop = ['expiration_dt']
        if not self.user.profile.is_superuser:
            fields_to_pop += [
                'slug',
                'entity',
                'allow_anonymous_view',
                'user_perms',
                'member_perms',
                'group_perms',
                'post_dt',
                'activation_dt',
                'syndicate',
                'status_detail'
            ]

        for f in list(set(fields_to_pop)):
            if f in self.fields:
                self.fields.pop(f)

    def clean_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False

    def clean_logo(self):
        logo = self.cleaned_data['logo']
        if logo:
            try:
                extension = splitext(logo.name)[1]

                # check the extension
                if extension.lower() not in ALLOWED_LOGO_EXT:
                    raise forms.ValidationError(_('The logo must be of jpg, gif, or png image type.'))

                # check the image header
                image_type = '.%s' % imghdr.what('', logo.read())
                if image_type not in ALLOWED_LOGO_EXT:
                    raise forms.ValidationError(_('The logo is an invalid image. Try uploading another logo.'))

                max_upload_size = get_max_file_upload_size()
                if logo.size > max_upload_size:
                    raise forms.ValidationError(_('Please keep filesize under %(max_upload_size)s. Current filesize %(logo_size)s') % {
                                                    'max_upload_size': filesizeformat(max_upload_size),
                                                    'logo_size': filesizeformat(logo.size)})
            except IOError:
                logo = None

        return logo

    def clean_headline(self):
        """
        remove extra leading and trailing white spaces
        """
        return self.cleaned_data.get('headline', '').strip()

    def save(self, *args, **kwargs):
        from tendenci.apps.files.models import File
        directory = super(DirectoryForm, self).save(*args, **kwargs)

        content_type = ContentType.objects.get(
                app_label=Directory._meta.app_label,
                model=Directory._meta.model_name)

        if 'pricing' in self.cleaned_data:
            directory.requested_duration = self.cleaned_data['pricing'].duration

        if self.cleaned_data['logo']:
            file_object, created = File.objects.get_or_create(
                file=self.cleaned_data['logo'],
                defaults={
                    'name': self.cleaned_data['logo'].name,
                    'content_type': content_type,
                    'object_id': directory.pk,
                    'is_public': directory.allow_anonymous_view,
                    'tags': directory.tags,
                    'creator': self.user,
                    'owner': self.user,
                })

            directory.logo_file = file_object
            directory.save(log=False)

        # clear logo; if box checked
        if self.cleaned_data['logo'] is False:
          directory.logo_file = None
          directory.save(log=False)
          File.objects.filter(
            content_type=content_type,
            object_id=directory.pk).delete()

        return directory