Esempio n. 1
0
File: admin.py Progetto: ixc/Misago
class EditUserForm(UserBaseForm):
    IS_STAFF_LABEL = _("Is administrator")
    IS_STAFF_HELP_TEXT = _(
        "Designates whether the user can log into admin sites. "
        "If Django admin site is enabled, this user will need "
        "additional permissions assigned within it to admin "
        "Django modules.")

    IS_SUPERUSER_LABEL = _("Is superuser")
    IS_SUPERUSER_HELP_TEXT = _("Only administrators can access admin sites. "
                               "In addition to admin site access, superadmins "
                               "can also change other members admin levels.")

    IS_ACTIVE_LABEL = _("Is active")
    IS_ACTIVE_HELP_TEXT = _(
        "Designates whether this user should be treated as active. "
        "Turning this off is non-destructible way to remove user accounts.")

    IS_ACTIVE_STAFF_MESSAGE_LABEL = _("Staff message")
    IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT = _(
        "Optional message for forum team members explaining "
        "why user's account has been disabled.")

    new_password = forms.CharField(
        label=_("Change password to"),
        strip=False,
        widget=forms.PasswordInput,
        required=False,
    )

    is_avatar_locked = YesNoSwitch(
        label=_("Lock avatar"),
        help_text=_("Setting this to yes will stop user from changing "
                    "his/her avatar, and will reset his/her avatar to "
                    "procedurally generated one."),
    )
    avatar_lock_user_message = forms.CharField(
        label=_("User message"),
        help_text=_("Optional message for user explaining "
                    "why he/she is banned form changing avatar."),
        widget=forms.Textarea(attrs={"rows": 3}),
        required=False,
    )
    avatar_lock_staff_message = forms.CharField(
        label=_("Staff message"),
        help_text=_("Optional message for forum team members explaining "
                    "why user is banned form changing avatar."),
        widget=forms.Textarea(attrs={"rows": 3}),
        required=False,
    )

    signature = forms.CharField(
        label=_("Signature contents"),
        widget=forms.Textarea(attrs={"rows": 3}),
        required=False,
    )
    is_signature_locked = YesNoSwitch(
        label=_("Lock signature"),
        help_text=_("Setting this to yes will stop user from "
                    "making changes to his/her signature."),
    )
    signature_lock_user_message = forms.CharField(
        label=_("User message"),
        help_text=
        _("Optional message to user explaining why his/hers signature is locked."
          ),
        widget=forms.Textarea(attrs={"rows": 3}),
        required=False,
    )
    signature_lock_staff_message = forms.CharField(
        label=_("Staff message"),
        help_text=
        _("Optional message to team members explaining why user signature is locked."
          ),
        widget=forms.Textarea(attrs={"rows": 3}),
        required=False,
    )

    is_hiding_presence = YesNoSwitch(label=_("Hides presence"))

    limits_private_thread_invites_to = forms.TypedChoiceField(
        label=_("Who can add user to private threads"),
        coerce=int,
        choices=User.LIMIT_INVITES_TO_CHOICES,
    )

    subscribe_to_started_threads = forms.TypedChoiceField(
        label=_("Started threads"),
        coerce=int,
        choices=User.SUBSCRIPTION_CHOICES)
    subscribe_to_replied_threads = forms.TypedChoiceField(
        label=_("Replid threads"),
        coerce=int,
        choices=User.SUBSCRIPTION_CHOICES)

    class Meta:
        model = User
        fields = [
            "username",
            "email",
            "title",
            "is_avatar_locked",
            "avatar_lock_user_message",
            "avatar_lock_staff_message",
            "signature",
            "is_signature_locked",
            "is_hiding_presence",
            "limits_private_thread_invites_to",
            "signature_lock_user_message",
            "signature_lock_staff_message",
            "subscribe_to_started_threads",
            "subscribe_to_replied_threads",
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        profilefields.add_fields_to_admin_form(self.request, self.instance,
                                               self)

    def get_profile_fields_groups(self):
        profile_fields_groups = []
        for group in self._profile_fields_groups:
            fields_group = {"name": group["name"], "fields": []}

            for fieldname in group["fields"]:
                fields_group["fields"].append(self[fieldname])

            profile_fields_groups.append(fields_group)
        return profile_fields_groups

    def clean_signature(self):
        data = self.cleaned_data["signature"]

        length_limit = self.settings.signature_length_max
        if len(data) > length_limit:
            message = ngettext(
                "Signature can't be longer than %(limit)s character.",
                "Signature can't be longer than %(limit)s characters.",
                length_limit,
            )
            raise forms.ValidationError(message % {"limit": length_limit})

        return data

    def clean(self):
        data = super().clean()
        return profilefields.clean_form(self.request, self.instance, self,
                                        data)
Esempio n. 2
0
class LicenseForm(AMOModelForm):
    builtin = forms.TypedChoiceField(
        choices=[],
        coerce=int,
        widget=LicenseRadioSelect(attrs={'class': 'license'}))
    name = forms.CharField(widget=TranslationTextInput(),
                           label=_(u'What is your license\'s name?'),
                           required=False,
                           initial=_('Custom License'))
    text = forms.CharField(widget=TranslationTextarea(),
                           required=False,
                           label=_(u'Provide the text of your license.'))

    def __init__(self, *args, **kwargs):
        self.version = kwargs.pop('version', None)
        if self.version:
            kwargs['instance'], kwargs['initial'] = self.version.license, None
            # Clear out initial data if it's a builtin license.
            if getattr(kwargs['instance'], 'builtin', None):
                kwargs['initial'] = {'builtin': kwargs['instance'].builtin}
                kwargs['instance'] = None
            self.cc_licenses = kwargs.pop(
                'cc', self.version.addon.type == amo.ADDON_STATICTHEME)
        else:
            self.cc_licenses = kwargs.pop('cc', False)

        super(LicenseForm, self).__init__(*args, **kwargs)
        licenses = License.objects.builtins(cc=self.cc_licenses).filter(
            on_form=True)
        cs = [(x.builtin, x) for x in licenses]
        if not self.cc_licenses:
            # creative commons licenses don't have an 'other' option.
            cs.append((License.OTHER, ugettext('Other')))
        self.fields['builtin'].choices = cs
        if (self.version
                and self.version.channel == amo.RELEASE_CHANNEL_UNLISTED):
            self.fields['builtin'].required = False

    class Meta:
        model = License
        fields = ('builtin', 'name', 'text')

    def clean_name(self):
        name = self.cleaned_data['name']
        return name.strip() or ugettext('Custom License')

    def clean(self):
        data = self.cleaned_data
        if self.errors:
            return data
        elif data['builtin'] == License.OTHER and not data['text']:
            raise forms.ValidationError(
                ugettext('License text is required when choosing Other.'))
        return data

    def get_context(self):
        """Returns a view context dict having keys license_form,
        and license_other_val.
        """
        return {
            'version': self.version,
            'license_form': self.version and self,
            'license_other_val': License.OTHER
        }

    def save(self, *args, **kw):
        """Save all form data.

        This will only create a new license if it's not one of the builtin
        ones.

        Keyword arguments

        **log=True**
            Set to False if you do not want to log this action for display
            on the developer dashboard.
        """
        log = kw.pop('log', True)
        changed = self.changed_data

        builtin = self.cleaned_data['builtin']
        if builtin == '':  # No license chosen, it must be an unlisted add-on.
            return
        is_other = builtin == License.OTHER
        if not is_other:
            # We're dealing with a builtin license, there is no modifications
            # allowed to it, just return it.
            license = License.objects.get(builtin=builtin)
        else:
            # We're not dealing with a builtin license, so save it to the
            # database.
            license = super(LicenseForm, self).save(*args, **kw)

        if self.version:
            if (changed and is_other) or license != self.version.license:
                self.version.update(license=license)
                if log:
                    ActivityLog.create(amo.LOG.CHANGE_LICENSE, license,
                                       self.version.addon)
        return license
Esempio n. 3
0
class SearchForm(forms.Form):
    """Django form for handling display and validation"""
    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)

        product_field = self.fields['product']
        product_field.choices = Product.objects.values_list('slug', 'title')

        topics_field = self.fields['topics']
        topics_field.choices = Topic.objects.values_list('slug',
                                                         'title').distinct()

    def clean(self):
        """Clean up data and set defaults"""
        c = self.cleaned_data

        if ('a' not in c or not c['a']) and c['q'] == '':
            raise ValidationError('Basic search requires a query string.')

        # Validate created and updated dates
        date_fields = (('created', 'created_date'), ('updated',
                                                     'updated_date'))
        for field_option, field_date in date_fields:
            if c[field_date] != '':
                try:
                    created_timestamp = time.mktime(
                        time.strptime(c[field_date], '%m/%d/%Y'))
                    c[field_date] = int(created_timestamp)
                except (ValueError, OverflowError):
                    c[field_option] = None
            else:
                c[field_option] = None

        # Empty value defaults to int
        c['num_votes'] = c.get('num_votes') or 0
        return c

    # Common fields
    q = forms.CharField(required=False)

    w = forms.TypedChoiceField(required=False,
                               coerce=int,
                               widget=forms.HiddenInput,
                               empty_value=constants.WHERE_BASIC,
                               choices=((constants.WHERE_SUPPORT,
                                         None), (constants.WHERE_WIKI, None),
                                        (constants.WHERE_BASIC, None),
                                        (constants.WHERE_DISCUSSION, None)))

    a = forms.IntegerField(required=False, widget=forms.HiddenInput)

    # KB fields
    topics = forms.MultipleChoiceField(required=False,
                                       widget=forms.CheckboxSelectMultiple(),
                                       label=_lazy(u'Topics'))

    language = forms.ChoiceField(required=False,
                                 label=_lazy(u'Language'),
                                 choices=SEARCH_LANGUAGES)

    category = TypedMultipleChoiceField(required=False,
                                        coerce=int,
                                        widget=forms.CheckboxSelectMultiple,
                                        label=_lazy(u'Category'),
                                        choices=CATEGORIES,
                                        coerce_only=True)

    product = forms.MultipleChoiceField(required=False,
                                        label=_lazy(u'Relevant to'),
                                        widget=forms.CheckboxSelectMultiple())

    include_archived = forms.BooleanField(
        required=False, label=_lazy(u'Include obsolete articles?'))

    sortby_documents = forms.TypedChoiceField(
        required=False,
        empty_value=constants.SORTBY_DOCUMENTS_CHOICES[0][0],
        label=_lazy(u'Sort results by'),
        choices=constants.SORTBY_DOCUMENTS_CHOICES)

    # Support questions and discussion forums fields
    created = forms.TypedChoiceField(required=False,
                                     coerce=int,
                                     empty_value=0,
                                     label=_lazy(u'Created'),
                                     choices=constants.DATE_LIST)

    created_date = forms.CharField(required=False)

    updated = forms.TypedChoiceField(required=False,
                                     coerce=int,
                                     empty_value=0,
                                     label=_lazy(u'Last updated'),
                                     choices=constants.DATE_LIST)
    updated_date = forms.CharField(required=False)

    user_widget = forms.TextInput(attrs={
        'placeholder': _lazy(u'username'),
        'class': 'auto-fill'
    })
    # Discussion forums fields
    author = forms.CharField(required=False, widget=user_widget)

    sortby = forms.TypedChoiceField(required=False,
                                    coerce=int,
                                    empty_value=0,
                                    label=_lazy(u'Sort results by'),
                                    choices=constants.SORTBY_FORUMS)

    thread_type = TypedMultipleChoiceField(
        required=False,
        coerce=int,
        widget=forms.CheckboxSelectMultiple,
        label=_lazy(u'Thread type'),
        choices=constants.DISCUSSION_STATUS_LIST,
        coerce_only=True)

    forum = TypedMultipleChoiceField(
        required=False,
        coerce=int,
        label=_lazy(u'Search in forum'),
        choices=[],  # Note: set choices with set_allowed_forums
        coerce_only=True)

    # Support questions fields
    asked_by = forms.CharField(required=False, widget=user_widget)
    answered_by = forms.CharField(required=False, widget=user_widget)

    sortby_questions = forms.TypedChoiceField(
        required=False,
        coerce=int,
        empty_value=0,
        label=_lazy(u'Sort results by'),
        choices=constants.SORTBY_QUESTIONS)

    is_locked = forms.TypedChoiceField(required=False,
                                       coerce=int,
                                       empty_value=0,
                                       widget=forms.RadioSelect,
                                       label=_lazy(u'Locked'),
                                       choices=constants.TERNARY_LIST)

    is_archived = forms.TypedChoiceField(required=False,
                                         coerce=int,
                                         empty_value=0,
                                         widget=forms.RadioSelect,
                                         label=_lazy(u'Archived'),
                                         choices=constants.TERNARY_LIST)

    is_solved = forms.TypedChoiceField(required=False,
                                       coerce=int,
                                       empty_value=0,
                                       widget=forms.RadioSelect,
                                       label=_lazy(u'Solved'),
                                       choices=constants.TERNARY_LIST)

    has_answers = forms.TypedChoiceField(required=False,
                                         coerce=int,
                                         empty_value=0,
                                         widget=forms.RadioSelect,
                                         label=_lazy(u'Has answers'),
                                         choices=constants.TERNARY_LIST)

    has_helpful = forms.TypedChoiceField(required=False,
                                         coerce=int,
                                         empty_value=0,
                                         widget=forms.RadioSelect,
                                         label=_lazy(u'Has helpful answers'),
                                         choices=constants.TERNARY_LIST)

    num_voted = forms.TypedChoiceField(required=False,
                                       coerce=int,
                                       empty_value=0,
                                       label=_lazy(u'Votes'),
                                       choices=constants.NUMBER_LIST)
    num_votes = forms.IntegerField(required=False)

    tag_widget = forms.TextInput(attrs={
        'placeholder': _lazy(u'tag1, tag2'),
        'class': 'auto-fill'
    })
    q_tags = forms.CharField(label=_lazy(u'Tags'),
                             required=False,
                             widget=tag_widget)

    def set_allowed_forums(self, user):
        """Sets the 'forum' field choices to forums the user can see."""
        forums = [(f.id, f.name)
                  for f in DiscussionForum.authorized_forums_for_user(user)]
        self.fields['forum'].choices = forums
Esempio n. 4
0
class TourPackageForm(forms.ModelForm):
    itinerary_type = forms.ModelChoiceField(
        queryset=ItineraryType.objects.all(),
        required=True,
        empty_label=None,
        widget=forms.RadioSelect,
        label='What type of itinerary is this?')

    country_indexes = forms.ModelMultipleChoiceField(
        queryset=CountryIndex.objects.all().order_by('name'),
        widget=forms.CheckboxSelectMultiple,
        label='Which countries will the itinerary visit?')

    safari_focus_activity = forms.ModelChoiceField(
        required=True,
        queryset=None,
        empty_label=None,
        widget=forms.RadioSelect(attrs={
            'class': 'col-4',
            'flat_attrs': 'col-4'
        }),
        label='Safari: what is the primary focus?')

    non_safari_focus_activity = forms.ModelChoiceField(
        required=True,
        queryset=None,
        label='Safari: what is the secondary focus?')

    secondary_focus_activity = forms.ModelMultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        queryset=None,
        label=
        'What are the highlights? <span class="text-warning">New feature! Showcase more aspects of your tours and reach your target audience.</span>'
    )

    parks = forms.ModelMultipleChoiceField(
        queryset=Park.objects.all().order_by('name'),
        required=True,
        widget=forms.CheckboxSelectMultiple,
        label='Which park(s) does this itinerary include?')

    title = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'maxlen',
            'maxlength': 100
        }),
        required=True,
        label='Tour package name',
        help_text=
        '<b>Example:</b> Serengeti, Tarangire and Lake Manyara camping safari. <br>*Don’t include number of days in title. It’s automatically pulled from this form.'
    )

    min_price = forms.CharField(label='Min price', required=True)
    max_price = forms.CharField(widget=forms.TextInput(),
                                label='Max price',
                                required=False)

    title_short = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'maxlen',
        'maxlength': 25
    }),
                                  required=True,
                                  label='Short title for search results',
                                  help_text='<b>Example:</b> Big five safari')

    # header = forms.CharField(
    #    widget=forms.Textarea(attrs={'rows':'3','class':'maxlen','maxlength':60}),
    #    required=True,
    #    label='Header',
    #    help_text='This will appear at the top of the page (above your itinerary fact sheet. Use this to grab our members attention)')

    summary = forms.CharField(
        widget=forms.Textarea(attrs={
            'rows': '3',
            'class': 'maxlen',
            'maxlength': 1000
        }),
        required=True,
        label='Summary',
        help_text='')

    content = forms.CharField(
        widget=forms.Textarea(attrs={
            'rows': '4',
            'class': 'maxlen',
            'maxlength': 100
        }),
        required=True,
        label='Day by day itinerary description',
        help_text=
        '<b>Please note:</b> Any formatting outside the YAS guidelines will be removed. For example: colored text or links will be automatically removed'
    )

    currency = forms.ModelChoiceField(queryset=Currency.objects.all(),
                                      label='Currency')

    days = forms.ChoiceField(choices=[
        (i, str(i) + (' day' if i == 1 else ' days')) for i in range(1, 19)
    ],
                             label='Length of safari',
                             help_text='')

    flight = forms.TypedChoiceField(
        coerce=lambda x: x == 'Yes',
        choices=((False, 'No'), (True, 'Yes')),
        widget=forms.RadioSelect,
        label='Do you do include internal flights?')

    single_supplement = forms.TypedChoiceField(
        coerce=lambda x: x == 'Yes',
        choices=((False, 'No'), (True, 'Yes')),
        widget=forms.RadioSelect,
        label='Do you charge a single supplement?')
    single_supplement_price = forms.CharField(required=True,
                                              label='Single suplement price',
                                              help_text='')

    inclusions = forms.ModelMultipleChoiceField(
        required=True,
        widget=forms.CheckboxSelectMultiple(attrs={'data-name': 'name'}),
        queryset=ItineraryInclusion.objects.all().order_by('name'),
        label="What's included? Select all that apply")

    other_inclusion = forms.CheckboxInput()

    other_inclusion_text = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'maxlen',
            'maxlength': 50,
            'placeholder': 'Other'
        }),
        required=True,
        label=False,
        help_text='')

    exclusions = forms.ModelMultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple(attrs={'data-name': 'name'}),
        queryset=ItineraryExclusion.objects.all().order_by('name'),
        label="What's excluded? Select all that apply")

    other_exclusion = forms.CheckboxInput()

    other_exclusion_text = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'maxlen',
            'maxlength': 50,
            'placeholder': 'Other'
        }),
        required=True,
        label=False,
        help_text='')

    months = forms.ModelMultipleChoiceField(
        required=True,
        widget=forms.CheckboxSelectMultiple,
        queryset=Month.objects.all(),
        label='Best time to visit')

    image = forms.ImageField(
        required=True,
        widget=forms.FileInput,
        label='Add an itinerary photo',
        help_text=
        'Please select a photo that is high quality (800x600) and representative of the tour. Landscape orientation works best'
    )
    accept_terms = forms.BooleanField(
        label='Accept the terms',
        help_text=
        'By using this photo, I claim I am the owner of these photos and you agree with our <a href="/terms-of-use/" target="_blank">terms of use</a>'
    )

    class Meta:
        model = Itinerary
        fields = '__all__'
        exclude = (
            'slug',
            'date_created',
        )

    def __init__(self, tour_operator=None, *args, **kwargs):
        super(TourPackageForm, self).__init__(*args, **kwargs)
        if tour_operator:
            self.fields[
                'country_indexes'].queryset = tour_operator.country_indexes.all(
                )
        usd, _ = Currency.objects.get_or_create(code='USD')
        self.fields['currency'].initial = usd
        primary = ItineraryFocusType.objects.get(name='Primary')
        self.fields[
            'safari_focus_activity'].queryset = primary.activities.filter(
                enabled=True).order_by('name')
        self.fields[
            'non_safari_focus_activity'].queryset = ItineraryFocusType.objects.get(
                name='Non safari').activities.filter(
                    enabled=True).order_by('name')
        self.fields[
            'secondary_focus_activity'].queryset = ItineraryFocusType.objects.get(
                name='Secondary').activities.filter(
                    enabled=True).order_by('name')
Esempio n. 5
0
class P3SubmissionForm(P3TalkFormMixin, cforms.SubmissionForm):
    duration = forms.TypedChoiceField(
        label=_('Duration'),
        help_text=_('This is the <b>desired duration</b> of the talk'),
        choices=TALK_DURATION,
        coerce=int,
        initial=60,
        required=False,
    )
    first_time = forms.BooleanField(
        label=_('I\'m a first-time speaker'),
        help_text=
        _('We are planning a special program to help first time speaker, check this if you\'d like to join'
          ),
        required=False,
    )
    type = forms.TypedChoiceField(
        label=_('Talk Type'),
        help_text=
        'Choose between a standard talk, a 4-hours in-depth training, a poster session or an help desk session',
        choices=(('s', 'Standard talk'), ('t', 'Training'),
                 ('p', 'Poster session'), ('h', 'Help Desk')),
        initial='s',
        required=True,
        widget=forms.RadioSelect(renderer=cforms.PseudoRadioRenderer),
    )
    personal_agreement = forms.BooleanField(
        label=
        _('I agree to let you publish my data (excluding birth date and phone number).'
          ),
        help_text=
        _('This speaker profile will be publicly accesible if one of your talks is accepted. Your mobile phone and date of birth will <strong>never</strong> be published'
          ),
    )
    slides_agreement = forms.BooleanField(
        label=_('I agree to release all the talk material after the event.'),
        help_text=
        _('If the talk is accepted, speakers a required to timely release all the talk material (including slides) for publishing on this web site.'
          ),
    )
    video_agreement = forms.BooleanField(label=_(
        'I agree to let the organization record my talk and publish the video.'
    ), )
    bio = forms.CharField(
        label=_('Compact biography'),
        help_text=
        _('Please enter a short biography (one or two paragraphs). Do not paste your CV!'
          ),
        widget=cforms.MarkEditWidget,
    )
    abstract = forms.CharField(
        max_length=5000,
        label=_('Talk abstract'),
        help_text=
        _('<p>Please enter a short description of the talk you are submitting. Be sure to includes the goals of your talk and any prerequisite required to fully understand it.</p><p>Suggested size: two or three paragraphs.</p>'
          ),
        widget=cforms.MarkEditWidget,
    )

    language = forms.TypedChoiceField(help_text=_(
        'Select Italian only if you are not comfortable in speaking English.'),
                                      choices=cmodels.TALK_LANGUAGES,
                                      initial='en',
                                      required=False)

    def __init__(self, user, *args, **kwargs):
        data = {
            'mobile': user.assopy_user.phone,
            'birthday': user.assopy_user.birthday,
            'activity_homepage': user.assopy_user.www,
        }
        data.update(kwargs.get('initial', {}))
        kwargs['initial'] = data
        super(P3SubmissionForm, self).__init__(user, *args, **kwargs)

    @transaction.commit_on_success
    def save(self, *args, **kwargs):
        talk = super(P3SubmissionForm, self).save(*args, **kwargs)

        speaker = self.user.speaker
        try:
            p3s = speaker.p3_speaker
        except models.SpeakerConference.DoesNotExist:
            p3s = models.SpeakerConference(speaker=speaker)

        data = self.cleaned_data

        p3s.first_time = data['first_time']
        p3s.save()

        return talk
Esempio n. 6
0
class ThemeReviewForm(forms.Form):
    theme = forms.ModelChoiceField(queryset=Persona.objects.all(),
                                   widget=forms.HiddenInput())
    action = forms.TypedChoiceField(
        choices=amo.REVIEW_ACTIONS.items(),
        widget=forms.HiddenInput(attrs={'class': 'action'}),
        coerce=int,
        empty_value=None)
    # Duplicate is the same as rejecting but has its own flow.
    reject_reason = forms.TypedChoiceField(
        choices=amo.THEME_REJECT_REASONS.items() + [('duplicate', '')],
        widget=forms.HiddenInput(attrs={'class': 'reject-reason'}),
        required=False,
        coerce=int,
        empty_value=None)
    comment = forms.CharField(
        required=False, widget=forms.HiddenInput(attrs={'class': 'comment'}))

    def clean_theme(self):
        theme = self.cleaned_data['theme']
        try:
            ThemeLock.objects.get(theme=theme)
        except ThemeLock.DoesNotExist:
            raise forms.ValidationError(
                ugettext('Someone else is reviewing this theme.'))
        return theme

    def clean_reject_reason(self):
        reject_reason = self.cleaned_data.get('reject_reason', None)
        if (self.cleaned_data.get('action') == amo.ACTION_REJECT
                and reject_reason is None):
            raise_required()
        return reject_reason

    def clean_comment(self):
        # Comment field needed for duplicate, flag, moreinfo, and other reject
        # reason.
        action = self.cleaned_data.get('action')
        reject_reason = self.cleaned_data.get('reject_reason')
        comment = self.cleaned_data.get('comment')
        if (not comment and
            (action == amo.ACTION_FLAG or action == amo.ACTION_MOREINFO or
             (action == amo.ACTION_REJECT and reject_reason == 0))):
            raise_required()
        return comment

    def save(self):
        action = self.cleaned_data['action']
        comment = self.cleaned_data.get('comment')
        reject_reason = self.cleaned_data.get('reject_reason')
        theme = self.cleaned_data['theme']

        is_rereview = (theme.rereviewqueuetheme_set.exists()
                       and theme.addon.status
                       not in (amo.STATUS_PENDING, amo.STATUS_REVIEW_PENDING))

        theme_lock = ThemeLock.objects.get(theme=self.cleaned_data['theme'])

        mail_and_log = True
        if action == amo.ACTION_APPROVE:
            if is_rereview:
                approve_rereview(theme)
            theme.addon.update(status=amo.STATUS_PUBLIC)
            theme.approve = datetime.datetime.now()
            theme.save()

        elif action in (amo.ACTION_REJECT, amo.ACTION_DUPLICATE):
            if is_rereview:
                reject_rereview(theme)
            else:
                theme.addon.update(status=amo.STATUS_REJECTED)

        elif action == amo.ACTION_FLAG:
            if is_rereview:
                mail_and_log = False
            else:
                theme.addon.update(status=amo.STATUS_REVIEW_PENDING)

        elif action == amo.ACTION_MOREINFO:
            if not is_rereview:
                theme.addon.update(status=amo.STATUS_REVIEW_PENDING)

        if mail_and_log:
            send_mail(self.cleaned_data, theme_lock)

            # Log.
            ActivityLog.create(amo.LOG.THEME_REVIEW,
                               theme.addon,
                               details={
                                   'theme': theme.addon.name.localized_string,
                                   'action': action,
                                   'reject_reason': reject_reason,
                                   'comment': comment
                               },
                               user=theme_lock.reviewer)
            log.info('%sTheme %s (%s) - %s' %
                     ('[Rereview] ' if is_rereview else '', theme.addon.name,
                      theme.id, action))

        score = 0
        if action in (amo.ACTION_REJECT, amo.ACTION_DUPLICATE,
                      amo.ACTION_APPROVE):
            score = ReviewerScore.award_points(theme_lock.reviewer,
                                               theme.addon, theme.addon.status)
        theme_lock.delete()

        return score
Esempio n. 7
0
class LWDeviceForm(forms.Form):
    """Form to process LoRaWAN devices that will be stored in the Sensor table"""
    DEVICE_CLASS = (
        ('A', 'A'),
        ('C', 'C'),
    )
    COUNTERS_SIZE_OPTIONS = (
        (2, 2),
        (4, 4),
    )

    name = forms.CharField(max_length=150, widget=mdl_textfield_widget)
    description = forms.CharField(max_length=255, widget=mdl_textfield_widget)

    # Device properties
    dev_class = forms.ChoiceField(choices=DEVICE_CLASS,
                                  initial='A',
                                  widget=mdl_select_widget,
                                  label="Device Class")
    counters_size = forms.TypedChoiceField(choices=COUNTERS_SIZE_OPTIONS,
                                           initial=4,
                                           widget=mdl_select_widget,
                                           coerce=int)

    # Device EUI - 64 bit end-device identifier, EUI-64 (unique)
    # DevEUI is assigned to the device by the chip manufacturer in LoRaWAN devices.
    # However, all communication is done using DevAddr (dynamic)
    dev_eui = forms.CharField(max_length=16,
                              validators=[
                                  RegexValidator(r"^[0-9a-fA-F]+$",
                                                 "Needs to be hexadecimal"),
                                  MinLengthValidator(16)
                              ],
                              label="Device EUI",
                              widget=forms.TextInput(
                                  attrs={
                                      'class': 'mdl-textfield__input',
                                      'pattern': '[0-9A-Fa-f]{16}',
                                      'placeholder': '16 hex characters',
                                      'title': '16 hex characters'
                                  }))

    # Application EUI - 64 bit end-device identifier, EUI-64 (unique)
    app_eui = forms.CharField(max_length=16,
                              validators=[
                                  RegexValidator(r"^[0-9a-fA-F]+$",
                                                 "Needs to be hexadecimal"),
                                  MinLengthValidator(16)
                              ],
                              label="Application EUI",
                              widget=forms.TextInput(
                                  attrs={
                                      'class': 'mdl-textfield__input',
                                      'pattern': '[0-9A-Fa-f]{16}',
                                      'placeholder': '16 hex characters',
                                      'title': '16 hex characters'
                                  }))

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

    def clean(self):
        cleaned_data = super(LWDeviceForm, self).clean()
        cleaned_data['dev_eui'] = cleaned_data['dev_eui'].lower()
        cleaned_data['sensor_id'] = cleaned_data['dev_eui']
        cleaned_data['sensor_type'] = 'lorawan'
        cleaned_data['user_id'] = self.user.id
        return cleaned_data
Esempio n. 8
0
class PublishForm(happyforms.Form):
    # Publish choice wording is slightly different here than with the
    # submission flow because the app may have already been published.
    mark_safe_lazy = lazy(mark_safe, six.text_type)
    PUBLISH_CHOICES = (
        (mkt.PUBLISH_IMMEDIATE,
         mark_safe_lazy(
             _lazy(
                 u'<b>Published</b>: Visible to everyone in the Marketplace and '
                 u'included in search results and listing pages.'))),
        (mkt.PUBLISH_HIDDEN,
         mark_safe_lazy(
             _lazy(u'<b>Unlisted</b>: Visible to only people with the URL and '
                   u'does not appear in search results and listing pages.'))),
    )

    # Used for setting initial form values.
    PUBLISH_MAPPING = {
        mkt.STATUS_PUBLIC: mkt.PUBLISH_IMMEDIATE,
        mkt.STATUS_UNLISTED: mkt.PUBLISH_HIDDEN,
        mkt.STATUS_APPROVED: mkt.PUBLISH_PRIVATE,
    }
    # Use in form processing to set status.
    STATUS_MAPPING = dict((v, k) for k, v in PUBLISH_MAPPING.items())

    publish_type = forms.TypedChoiceField(required=False,
                                          choices=PUBLISH_CHOICES,
                                          widget=forms.RadioSelect(),
                                          initial=0,
                                          coerce=int,
                                          label=_lazy('App Visibility:'))
    limited = forms.BooleanField(
        required=False,
        label=_lazy(u'<b>Limit to my team</b>: Visible to only Team Members.'))

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

        limited = False
        publish = self.PUBLISH_MAPPING.get(self.addon.status,
                                           mkt.PUBLISH_IMMEDIATE)
        if self.addon.status == mkt.STATUS_APPROVED:
            # Special case if app is currently private.
            limited = True
            publish = mkt.PUBLISH_HIDDEN

        # Determine the current selection via STATUS to publish choice mapping.
        self.fields['publish_type'].initial = publish
        self.fields['limited'].initial = limited

        # Make the limited label safe so we can display the HTML.
        self.fields['limited'].label = mark_safe(self.fields['limited'].label)

    def save(self):
        publish = self.cleaned_data['publish_type']
        limited = self.cleaned_data['limited']

        if publish == mkt.PUBLISH_HIDDEN and limited:
            publish = mkt.PUBLISH_PRIVATE

        status = self.STATUS_MAPPING[publish]
        self.addon.update(status=status)

        mkt.log(mkt.LOG.CHANGE_STATUS, self.addon.get_status_display(),
                self.addon)
        # Call update_version, so various other bits of data update.
        self.addon.update_version()
        # Call to update names and locales if changed.
        self.addon.update_name_from_package_manifest()
        self.addon.update_supported_locales()

        if waffle.switch_is_active('iarc-upgrade-v2'):
            iarc_publish.delay(self.addon.pk)
        else:
            set_storefront_data.delay(self.addon.pk)
Esempio n. 9
0
class RegionForm(forms.Form):
    regions = forms.MultipleChoiceField(
        required=False,
        choices=[],
        widget=forms.CheckboxSelectMultiple,
        label=_lazy(u'Choose the regions your app will be listed in:'),
        error_messages={
            'required': _lazy(u'You must select at least one region.')
        })
    enable_new_regions = forms.BooleanField(required=False,
                                            label=_lazy(u'Enable new regions'))
    restricted = forms.TypedChoiceField(
        required=False,
        initial=0,
        coerce=int,
        choices=[(0, _lazy('Make my app available in most regions')),
                 (1, _lazy('Choose where my app is made available'))],
        widget=forms.RadioSelect(attrs={'class': 'choices'}))

    def __init__(self, *args, **kw):
        self.product = kw.pop('product', None)
        self.request = kw.pop('request', None)
        super(RegionForm, self).__init__(*args, **kw)

        self.fields['regions'].choices = REGIONS_CHOICES_SORTED_BY_NAME()

        # This is the list of the user's exclusions as we don't
        # want the user's choices to be altered by external
        # exclusions e.g. payments availability.
        user_exclusions = list(
            self.product.addonexcludedregion.values_list('region', flat=True))

        # If we have excluded regions, uncheck those.
        # Otherwise, default to everything checked.
        self.regions_before = self.product.get_region_ids(
            restofworld=True, excluded=user_exclusions)

        self.initial = {
            'regions': sorted(self.regions_before),
            'restricted': int(self.product.geodata.restricted),
            'enable_new_regions': self.product.enable_new_regions,
        }

    @property
    def regions_by_id(self):
        return mkt.regions.REGIONS_CHOICES_ID_DICT

    def is_toggling(self):
        if not self.request or not hasattr(self.request, 'POST'):
            return False
        return self.product.premium_type != mkt.ADDON_FREE

    def _product_is_paid(self):
        return (self.product.premium_type in mkt.ADDON_PREMIUMS
                or self.product.premium_type == mkt.ADDON_FREE_INAPP)

    def clean_regions(self):
        regions = self.cleaned_data['regions']
        if not self.is_toggling():
            if not regions:
                raise forms.ValidationError(
                    _('You must select at least one region.'))
        return regions

    def save(self):
        # Don't save regions if we are toggling.
        if self.is_toggling():
            return

        regions = [int(x) for x in self.cleaned_data['regions']]
        restricted = int(self.cleaned_data['restricted'] or 0)

        if restricted:
            before = set(self.regions_before)
            after = set(regions)

            log.info(u'[Webapp:%s] App marked as restricted.' % self.product)

            # Add new region exclusions.
            to_add = before - after
            for region in to_add:
                aer, created = self.product.addonexcludedregion.get_or_create(
                    region=region)
                if created:
                    log.info(u'[Webapp:%s] Excluded from new region (%s).' %
                             (self.product, region))

            # Remove old region exclusions.
            to_remove = after - before
            for region in to_remove:
                self.product.addonexcludedregion.filter(region=region).delete()
                log.info(u'[Webapp:%s] No longer excluded from region (%s).' %
                         (self.product, region))

            # If restricted, check how we should handle new regions.
            if self.cleaned_data['enable_new_regions']:
                self.product.update(enable_new_regions=True)
                log.info(u'[Webapp:%s] will be added to future regions.' %
                         self.product)
            else:
                self.product.update(enable_new_regions=False)
                log.info(u'[Webapp:%s] will not be added to future regions.' %
                         self.product)
        else:
            # If not restricted, set `enable_new_regions` to True and remove
            # currently excluded regions.
            self.product.update(enable_new_regions=True)
            self.product.addonexcludedregion.all().delete()
            log.info(u'[Webapp:%s] App marked as unrestricted.' % self.product)

        self.product.geodata.update(restricted=restricted)
Esempio n. 10
0
class InterestForm(forms.Form):
    interested = forms.TypedChoiceField(widget=forms.RadioSelect, coerce=int, choices=((1, "Yes"), (0, "No")))
    age = forms.IntegerField(initial=20)
    comments = forms.CharField(widget=forms.Textarea, label='Additional Comments', required=False)
Esempio n. 11
0
class SignupForm(forms.ModelForm, FormWithReCaptcha):
    password = forms.CharField(
        widget=forms.PasswordInput,
        label=pgettext('Password', 'Password'))
    confirm_password = forms.CharField(widget=forms.PasswordInput(),
                                       label=pgettext('Confirm Password',
                                                      'Confirm Password'))
    email = forms.EmailField(
        label=pgettext('Email', 'Email'),
        error_messages={
            'unique': pgettext_lazy(
                'Registration error',
                'This email has already been registered.')})
    full_name = forms.CharField(widget=forms.TextInput,
                                label=pgettext('Full name', 'Full name'))
    birthday = forms.DateField(widget=forms.DateInput(format='%Y-%m-%d'),
                               label=pgettext('Date of birth', 'Date of birth'),
                               input_formats=('%Y-%m-%d',))
    phone = forms.CharField(widget=forms.TextInput,
                            label=pgettext('Phone Number', 'Phone Number'))
    address = forms.CharField(widget=forms.TextInput,
                              label=pgettext('Address', 'Address'))
    billing_address = forms.CharField(widget=forms.TextInput,
                                      label=pgettext('Billing Address',
                                                     'Billing Address'))
    SEX_CHOICES = (('man', 'Man'), ('woman', 'Woman'))
    sex = forms.TypedChoiceField(choices=SEX_CHOICES, widget=forms.RadioSelect)
    COMPANY_CHOICES = (('individual', 'Individual'), ('industry', 'Industry'))
    company = forms.TypedChoiceField(choices=COMPANY_CHOICES, widget=forms.RadioSelect)

    error_messages = {
        'password_mismatch': "The two password fields didn't match.",
    }

    class Meta:
        model = User
        fields = ('email', 'full_name', 'birthday', 'phone', 'address',
                  'billing_address')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self._meta.model.USERNAME_FIELD in self.fields:
            self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update(
                {'autofocus': ''})

    def save(self, request=None, commit=True):
        user = super().save(commit=False)
        password = self.cleaned_data['password']
        user.set_password(password)
        if commit:
            user.save()
        return user

    def clean(self):
        cleaned_data = super(SignupForm, self).clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")

        if password and confirm_password and password != confirm_password:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return self.cleaned_data
Esempio n. 12
0
class CakeForm(forms.Form):
    message = forms.CharField(max_length=128)
    cake_type = forms.TypedChoiceField(choices=Cake.CAKE_TYPE_CHOICES,
                                       coerce=int)
Esempio n. 13
0
class PremiumForm(happyforms.Form):
    """
    The premium details for an addon, which is unfortunately
    distributed across a few models.
    """
    paypal_id = forms.CharField()
    price = forms.ModelChoiceField(queryset=Price.objects.active(),
                                   label=_lazy(u'Add-on price'),
                                   empty_label=None)
    do_upsell = forms.TypedChoiceField(coerce=lambda x: bool(int(x)),
                                       choices=UPSELL_CHOICES,
                                       widget=forms.RadioSelect(),
                                       required=False)
    free = forms.ModelChoiceField(queryset=Addon.objects.none(),
                                  required=False,
                                  empty_label='')
    support_email = forms.EmailField()

    def __init__(self, *args, **kw):
        self.extra = kw.pop('extra')
        self.request = kw.pop('request')
        self.addon = self.extra['addon']
        kw['initial'] = {
            'paypal_id': self.addon.paypal_id,
            'support_email': self.addon.support_email,
            'do_upsell': 0,
        }
        if self.addon.premium:
            kw['initial']['price'] = self.addon.premium.price

        upsell = self.addon.upsold
        if upsell:
            kw['initial'].update({
                'free': upsell.free,
                'do_upsell': 1,
            })

        super(PremiumForm, self).__init__(*args, **kw)
        if self.addon.is_webapp():
            self.fields['price'].label = loc('App price')
            self.fields['do_upsell'].choices = APP_UPSELL_CHOICES
        self.fields['free'].queryset = (self.extra['amo_user'].addons
                                        .exclude(pk=self.addon.pk)
                                        .filter(premium_type=amo.ADDON_FREE,
                                                type=self.addon.type))

        # For the wizard, we need to remove some fields.
        for field in self.extra.get('exclude', []):
            del self.fields[field]

    def _show_token_msg(self, message):
        """Display warning for an invalid PayPal refund token."""
        url = paypal.get_permission_url(self.addon,
                                        self.extra.get('dest', 'payment'),
                                        ['REFUND'])
        msg = _(' <a href="%s">Visit PayPal to grant permission'
                ' for refunds on your behalf.</a>') % url
        messages.warning(self.request, '%s %s' % (message, Markup(msg)))
        raise forms.ValidationError(message)

    def clean_paypal_id(self):
        paypal_id = self.cleaned_data['paypal_id']
        # Check it's a valid paypal id.
        check_paypal_id(paypal_id)

        if (self.addon.paypal_id and self.addon.paypal_id != paypal_id
            and self.addon.premium
            and self.addon.premium.has_permissions_token()):
            # If a user changes their paypal id, then we need
            # to nuke the token, but don't do this when it's is blank.
            self.addon.premium.paypal_permissions_token = ''
            self.addon.premium.save()

        return paypal_id

    def clean(self):
        paypal_id = self.cleaned_data.get('paypal_id', '')
        if paypal_id:
            # If we're going to prompt for refund permission, we need to
            # record the PayPal ID first.
            self.addon.paypal_id = paypal_id
            self.addon.save()
        # Check if third-party refund token is properly set up.
        no_token = (not self.addon.premium or
                    not self.addon.premium.has_permissions_token())
        invalid_token = (self.addon.premium and
                         not self.addon.premium.has_valid_permissions_token())
        if no_token or invalid_token:
            # L10n: We require PayPal users to have a third-party token set up.
            self._show_token_msg(loc('PayPal third-party refund token has not '
                                     'been set up or has recently expired.'))
        return self.cleaned_data

    def clean_free(self):
        if self.cleaned_data['do_upsell'] and not self.cleaned_data['free']:
            raise_required()
        return self.cleaned_data['free']

    def save(self):
        if 'paypal_id' in self.cleaned_data:
            self.addon.paypal_id = self.cleaned_data['paypal_id']
            self.addon.support_email = self.cleaned_data['support_email']
            self.addon.save()

        if 'price' in self.cleaned_data:
            premium = self.addon.premium
            if not premium:
                premium = AddonPremium()
                premium.addon = self.addon
            premium.price = self.cleaned_data['price']
            premium.save()

        upsell = self.addon.upsold
        if self.cleaned_data['do_upsell'] and self.cleaned_data['free']:

            # Check if this app was already a premium version for another app.
            if upsell and upsell.free != self.cleaned_data['free']:
                upsell.delete()

            if not upsell:
                upsell = AddonUpsell(premium=self.addon)
            upsell.free = self.cleaned_data['free']
            upsell.save()
        elif not self.cleaned_data['do_upsell'] and upsell:
            upsell.delete()
Esempio n. 14
0
class UserEditForm(UserRegisterForm, PasswordMixin):
    oldpassword = forms.CharField(
        max_length=255,
        required=False,
        widget=forms.PasswordInput(render_value=False))
    password = forms.CharField(max_length=255,
                               required=False,
                               min_length=PasswordMixin.min_length,
                               error_messages=PasswordMixin.error_msg,
                               widget=PasswordMixin.widget(render_value=False))

    password2 = forms.CharField(max_length=255,
                                required=False,
                                widget=forms.PasswordInput(render_value=False))

    photo = forms.FileField(label=_lazy(u'Profile Photo'), required=False)

    notifications = forms.MultipleChoiceField(
        choices=[],
        widget=NotificationsSelectMultiple,
        initial=email.NOTIFICATIONS_DEFAULT,
        required=False)

    lang = forms.TypedChoiceField(label=_lazy(u'Default locale'),
                                  choices=LOCALES)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(UserEditForm, self).__init__(*args, **kwargs)

        if not self.instance.lang and self.request:
            self.initial['lang'] = self.request.LANG

        if self.instance:
            default = dict((i, n.default_checked)
                           for i, n in email.NOTIFICATIONS_BY_ID.items())
            user = dict((n.notification_id, n.enabled)
                        for n in self.instance.notifications.all())
            default.update(user)

            # Add choices to Notification.
            choices = email.NOTIFICATIONS_CHOICES
            if not self.instance.is_developer:
                choices = email.NOTIFICATIONS_CHOICES_NOT_DEV

            # Append a "NEW" message to new notification options.
            saved = self.instance.notifications.values_list('notification_id',
                                                            flat=True)
            self.choices_status = {}
            for idx, label in choices:
                self.choices_status[idx] = idx not in saved

            self.fields['notifications'].choices = choices
            self.fields['notifications'].initial = [
                i for i, v in default.items() if v
            ]
            self.fields['notifications'].widget.form_instance = self

        # TODO: We should inherit from a base form not UserRegisterForm
        if self.fields.get('recaptcha'):
            del self.fields['recaptcha']

    class Meta:
        model = UserProfile
        exclude = ('password', 'picture_type', 'last_login')

    def clean(self):
        data = self.cleaned_data
        amouser = self.request.user

        # Passwords
        p1 = data.get("password")
        p2 = data.get("password2")

        if p1 or p2:
            if not amouser.check_password(data["oldpassword"]):
                msg = _("Wrong password entered!")
                self._errors["oldpassword"] = ErrorList([msg])
                del data["oldpassword"]

        super(UserEditForm, self).clean()
        return data

    def clean_photo(self):
        photo = self.cleaned_data['photo']

        if not photo:
            return

        if photo.content_type not in ('image/png', 'image/jpeg'):
            raise forms.ValidationError(_('Images must be either PNG or JPG.'))

        if photo.size > settings.MAX_PHOTO_UPLOAD_SIZE:
            raise forms.ValidationError(
                _('Please use images smaller than %dMB.' %
                  (settings.MAX_PHOTO_UPLOAD_SIZE / 1024 / 1024 - 1)))

        return photo

    def clean_bio(self):
        bio = self.cleaned_data['bio']
        normalized = clean_nl(unicode(bio))
        if has_links(normalized):
            # There's some links, we don't want them.
            raise forms.ValidationError(_('No links are allowed.'))
        return bio

    def save(self, log_for_developer=True):
        u = super(UserEditForm, self).save(commit=False)
        data = self.cleaned_data
        photo = data['photo']
        if photo:
            u.picture_type = 'image/png'
            tmp_destination = u.picture_path + '__unconverted'

            with storage.open(tmp_destination, 'wb') as fh:
                for chunk in photo.chunks():
                    fh.write(chunk)

            tasks.resize_photo.delay(tmp_destination,
                                     u.picture_path,
                                     set_modified_on=[u])

        if data['password']:
            u.set_password(data['password'])
            log_cef('Password Changed',
                    5,
                    self.request,
                    username=u.username,
                    signature='PASSWORDCHANGED',
                    msg='User changed password')
            if log_for_developer:
                amo.log(amo.LOG.CHANGE_PASSWORD)
                log.info(u'User (%s) changed their password' % u)

        for (i, n) in email.NOTIFICATIONS_BY_ID.items():
            enabled = n.mandatory or (str(i) in data['notifications'])
            UserNotification.update_or_create(user=u,
                                              notification_id=i,
                                              update={'enabled': enabled})

        log.debug(u'User (%s) updated their profile' % u)

        u.save()
        return u
Esempio n. 15
0
class CartAddProductForm(forms.Form):
    quantity = forms.TypedChoiceField(label='Количество:', choices=PRODUCT_QUANTITY_CHOICES, coerce=int,
    widget=forms.Select(
        attrs={'class': 'form-control'}
        ))
    update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)
Esempio n. 16
0
class CartAddProductForm(forms.Form):
    quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES,
                                      coerce=int, label=_('Quantity'))  # converse input into integer
    update = forms.BooleanField(
        required=False, initial=False, widget=forms.HiddenInput)
Esempio n. 17
0
class MonsterImportOptionsMixin(forms.Form):
    missing_choices = ((1, 'Delete missing'), (0, 'Do not delete'))

    missing_monster_action = forms.TypedChoiceField(
        label='Action for monsters not in import data',
        initial=1,
        required=True,
        choices=missing_choices,
        widget=forms.RadioSelect,
        coerce=int,
    )
    missing_rune_action = forms.TypedChoiceField(
        label='Action for runes not in import data',
        initial=1,
        required=True,
        choices=missing_choices,
        widget=forms.RadioSelect,
        coerce=int,
    )
    clear_profile = forms.BooleanField(
        required=False,
        label=
        'Clear entire profile on import. This is recommended for the first Com2US data import. All your notes, priorities, and teams will be lost!',
        help_text='')
    default_priority = forms.ChoiceField(
        label='Default Priority for new monsters',
        choices=BLANK_CHOICE_DASH + MonsterInstance.PRIORITY_CHOICES,
        required=False,
    )
    minimum_stars = forms.ChoiceField(
        label='Minimum stars',
        choices=Monster.STAR_CHOICES,
        required=True,
        widget=forms.RadioSelect,
        initial=1,
    )
    ignore_silver = forms.BooleanField(
        required=False,
        label="Ignore silver star monsters that can't be awakened")
    ignore_material = forms.BooleanField(
        required=False,
        label=
        "Ignore material type monsters (Rainbowmon, Angelmon, and Devilmon)")
    except_with_runes = forms.BooleanField(
        required=False,
        label='Import anyway if monster has equipped runes',
        initial=True,
    )
    except_light_and_dark = forms.BooleanField(
        required=False,
        label='Import anyway if monster is Light or Dark',
        initial=True,
    )
    lock_monsters = forms.BooleanField(
        required=False,
        label=mark_safe(
            '<span class="glyphicon glyphicon-lock"></span> Copy locked status of monsters from in-game'
        ),
        help_text=
        'Locking on SWARFARM means a monster will not be used as fusion ingredients or skill-ups.',
        initial=True,
    )
    ignore_validation = forms.BooleanField(
        required=False,
        label='Ignore validation checks',
        initial=False,
    )
Esempio n. 18
0
class LicenseForm(AMOModelForm):
    builtin = forms.TypedChoiceField(
        choices=[], coerce=int,
        widget=LicenseRadioSelect(attrs={'class': 'license'}))
    name = forms.CharField(widget=TranslationTextInput(),
                           label=_lazy(u"What is your license's name?"),
                           required=False, initial=_lazy('Custom License'))
    text = forms.CharField(widget=TranslationTextarea(), required=False,
                           label=_lazy(u'Provide the text of your license.'))

    def __init__(self, *args, **kw):
        addon = kw.pop('addon', None)
        self.version = None
        if addon:
            self.version = addon.latest_version
            if self.version:
                kw['instance'], kw['initial'] = self.version.license, None
                # Clear out initial data if it's a builtin license.
                if getattr(kw['instance'], 'builtin', None):
                    kw['initial'] = {'builtin': kw['instance'].builtin}
                    kw['instance'] = None

        super(LicenseForm, self).__init__(*args, **kw)

        cs = [(x.builtin, x)
              for x in License.objects.builtins().filter(on_form=True)]
        cs.append((License.OTHER, _('Other')))
        self.fields['builtin'].choices = cs
        if addon and not addon.is_listed:
            self.fields['builtin'].required = False

    class Meta:
        model = License
        fields = ('builtin', 'name', 'text')

    def clean_name(self):
        name = self.cleaned_data['name']
        return name.strip() or _('Custom License')

    def clean(self):
        data = self.cleaned_data
        if self.errors:
            return data
        elif data['builtin'] == License.OTHER and not data['text']:
            raise forms.ValidationError(
                _('License text is required when choosing Other.'))
        return data

    def get_context(self):
        """Returns a view context dict having keys license_urls, license_form,
        and license_other_val.
        """
        license_urls = dict(License.objects.builtins()
                            .values_list('builtin', 'url'))
        return dict(license_urls=license_urls, version=self.version,
                    license_form=self.version and self,
                    license_other_val=License.OTHER)

    def save(self, *args, **kw):
        """Save all form data.

        This will only create a new license if it's not one of the builtin
        ones.

        Keyword arguments

        **log=True**
            Set to False if you do not want to log this action for display
            on the developer dashboard.
        """
        log = kw.pop('log', True)
        changed = self.changed_data

        builtin = self.cleaned_data['builtin']
        if builtin == '':  # No license chosen, it must be an unlisted add-on.
            return
        if builtin != License.OTHER:
            license = License.objects.get(builtin=builtin)
        else:
            # Save the custom license:
            license = super(LicenseForm, self).save(*args, **kw)

        if self.version:
            if changed or license != self.version.license:
                self.version.update(license=license)
                if log:
                    amo.log(amo.LOG.CHANGE_LICENSE, license,
                            self.version.addon)
        return license
Esempio n. 19
0
class TenantBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
    pk = forms.ModelMultipleChoiceField(queryset=Tenant.objects.all(), widget=forms.MultipleHiddenInput)
    group = forms.TypedChoiceField(choices=bulkedit_tenantgroup_choices, coerce=int, required=False, label='Group')
Esempio n. 20
0
class BanForm(forms.ModelForm):
    check_type = forms.TypedChoiceField(
        label=_("Check type"),
        coerce=int,
        choices=Ban.CHOICES,
    )
    registration_only = YesNoSwitch(
        label=_("Restrict this ban to registrations"),
        help_text=
        _("Changing this to yes will make this ban check be only performed on registration "
          "step. This is good if you want to block certain registrations like ones from "
          "recently comprimised e-mail providers, without harming existing users."
          ),
    )
    banned_value = forms.CharField(
        label=_("Banned value"),
        max_length=250,
        help_text=_('This value is case-insensitive and accepts asterisk (*) '
                    'for rought matches. For example, making IP ban for value '
                    '"83.*" will ban all IP addresses beginning with "83.".'),
        error_messages={
            'max_length':
            _("Banned value can't be longer than 250 characters."),
        })
    user_message = forms.CharField(
        label=_("User message"),
        required=False,
        max_length=1000,
        help_text=_(
            "Optional message displayed to user instead of default one."),
        widget=forms.Textarea(attrs={'rows': 3}),
        error_messages={
            'max_length': _("Message can't be longer than 1000 characters."),
        })
    staff_message = forms.CharField(
        label=_("Team message"),
        required=False,
        max_length=1000,
        help_text=_("Optional ban message for moderators and administrators."),
        widget=forms.Textarea(attrs={'rows': 3}),
        error_messages={
            'max_length': _("Message can't be longer than 1000 characters."),
        })
    expires_on = IsoDateTimeField(
        label=_("Expires on"),
        required=False,
        help_text=_("Leave this field empty for this ban to never expire."))

    class Meta:
        model = Ban
        fields = [
            'check_type',
            'registration_only',
            'banned_value',
            'user_message',
            'staff_message',
            'expires_on',
        ]

    def clean_banned_value(self):
        data = self.cleaned_data['banned_value']
        while '**' in data:
            data = data.replace('**', '*')

        if data == '*':
            raise forms.ValidationError(_("Banned value is too vague."))

        return data
Esempio n. 21
0
class CartAddProductForm(forms.Form):
    quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES,
                                      coerce=int)
    update = forms.BooleanField(required=False,
                                initial=False,
                                widget=forms.HiddenInput)
Esempio n. 22
0
class EditUserForm(UserBaseForm):
    IS_STAFF_LABEL = _("Is administrator")
    IS_STAFF_HELP_TEXT = _(
        "Designates whether the user can log into admin sites. "
        "If Django admin site is enabled, this user will need "
        "additional permissions assigned within it to admin "
        "Django modules.")

    IS_SUPERUSER_LABEL = _("Is superuser")
    IS_SUPERUSER_HELP_TEXT = _("Only administrators can access admin sites. "
                               "In addition to admin site access, superadmins "
                               "can also change other members admin levels.")

    IS_ACTIVE_LABEL = _('Is active')
    IS_ACTIVE_HELP_TEXT = _(
        "Designates whether this user should be treated as active. "
        "Turning this off is non-destructible way to remove user accounts.")

    IS_ACTIVE_STAFF_MESSAGE_LABEL = _("Staff message")
    IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT = _(
        "Optional message for forum team members explaining "
        "why user's account has been disabled.")

    new_password = forms.CharField(
        label=_("Change password to"),
        widget=forms.PasswordInput,
        required=False,
    )

    is_avatar_locked = YesNoSwitch(
        label=_("Lock avatar"),
        help_text=_("Setting this to yes will stop user from changing "
                    "his/her avatar, and will reset his/her avatar to "
                    "procedurally generated one."))
    avatar_lock_user_message = forms.CharField(
        label=_("User message"),
        help_text=_("Optional message for user explaining "
                    "why he/she is banned form changing avatar."),
        widget=forms.Textarea(attrs={'rows': 3}),
        required=False)
    avatar_lock_staff_message = forms.CharField(
        label=_("Staff message"),
        help_text=_("Optional message for forum team members explaining "
                    "why user is banned form changing avatar."),
        widget=forms.Textarea(attrs={'rows': 3}),
        required=False)

    signature = forms.CharField(
        label=_("Signature contents"),
        widget=forms.Textarea(attrs={'rows': 3}),
        required=False,
    )
    is_signature_locked = YesNoSwitch(
        label=_("Lock signature"),
        help_text=_("Setting this to yes will stop user from "
                    "making changes to his/her signature."))
    signature_lock_user_message = forms.CharField(
        label=_("User message"),
        help_text=
        _("Optional message to user explaining why his/hers signature is locked."
          ),
        widget=forms.Textarea(attrs={'rows': 3}),
        required=False)
    signature_lock_staff_message = forms.CharField(
        label=_("Staff message"),
        help_text=
        _("Optional message to team members explaining why user signature is locked."
          ),
        widget=forms.Textarea(attrs={'rows': 3}),
        required=False)

    is_hiding_presence = YesNoSwitch(label=_("Hides presence"))

    limits_private_thread_invites_to = forms.TypedChoiceField(
        label=_("Who can add user to private threads"),
        coerce=int,
        choices=UserModel.LIMIT_INVITES_TO_CHOICES)

    subscribe_to_started_threads = forms.TypedChoiceField(
        label=_("Started threads"),
        coerce=int,
        choices=UserModel.SUBSCRIBE_CHOICES)
    subscribe_to_replied_threads = forms.TypedChoiceField(
        label=_("Replid threads"),
        coerce=int,
        choices=UserModel.SUBSCRIBE_CHOICES)

    class Meta:
        model = UserModel
        fields = [
            'username',
            'email',
            'title',
            'is_avatar_locked',
            'avatar_lock_user_message',
            'avatar_lock_staff_message',
            'signature',
            'is_signature_locked',
            'is_hiding_presence',
            'limits_private_thread_invites_to',
            'signature_lock_user_message',
            'signature_lock_staff_message',
            'subscribe_to_started_threads',
            'subscribe_to_replied_threads',
        ]

    def clean_signature(self):
        data = self.cleaned_data['signature']

        length_limit = settings.signature_length_max
        if len(data) > length_limit:
            raise forms.ValidationError(
                ungettext(
                    "Signature can't be longer than %(limit)s character.",
                    "Signature can't be longer than %(limit)s characters.",
                    length_limit,
                ) % {'limit': length_limit})

        return data
Esempio n. 23
0
class UserProfileForm(forms.Form):
    poldnev_person = poldnev_forms.PersonField(
        label='Бывали ли вы в ЛКШ?',
        help_text='Оставьте поле пустым, если ещё не были в ЛКШ',
        required=False,
    )

    last_name = forms.CharField(
        required=True,
        label='Фамилия',
        help_text='Как в паспорте или свидетельстве о рождении',
        max_length=100,
        widget=TextInputWithFaIcon(attrs={
            'placeholder': 'Введите фамилию',
            'class': 'gui-input',
            'fa': 'user',
        }))

    first_name = forms.CharField(
        required=True,
        label='Имя',
        help_text='Как в паспорте или свидетельстве о рождении',
        max_length=100,
        widget=TextInputWithFaIcon(attrs={
            'placeholder': 'Введите имя',
            'class': 'gui-input',
            'fa': 'user',
        }))

    middle_name = forms.CharField(
        required=False,
        label='Отчество',
        help_text='Как в паспорте или свидетельстве о рождении',
        max_length=100,
        widget=TextInputWithFaIcon(
            attrs={
                'placeholder': 'Введите отчество',
                'class': 'gui-input',
                'fa': 'user',
            }))

    sex = forms.TypedChoiceField(
        choices=models.UserProfile.Sex.choices,
        required=True,
        label='Пол',
        widget=SistemaRadioSelect(attrs={'inline': True}),
        coerce=int,
    )

    birth_date = forms.DateField(required=True,
                                 label='Дата рождения',
                                 widget=forms.DateInput(
                                     attrs={
                                         'class': 'gui-input datetimepicker',
                                         'data-format': 'DD.MM.YYYY',
                                         'data-view-mode': 'years',
                                         'data-pick-time': 'false',
                                         'placeholder': 'дд.мм.гггг',
                                     }))

    current_class = forms.IntegerField(
        required=True,
        label='Класс',
        help_text=models.UserProfile.get_class_help_text(),
        min_value=1,
        widget=forms.NumberInput(attrs={'class': 'gui-input'}))

    region = forms.CharField(
        required=True,
        label='Субъект РФ',
        help_text='или страна, если не Россия',
        max_length=100,
        widget=TextInputWithFaIcon(
            attrs={
                'class': 'gui-input',
                'fa': 'building-o',
                'placeholder': 'Например, Москва или Тюменская область'
            }))

    city = forms.CharField(required=True,
                           label='Населённый пункт',
                           help_text='в котором находится школа',
                           max_length=100,
                           widget=TextInputWithFaIcon(
                               attrs={
                                   'placeholder': 'Город, деревня, село..',
                                   'class': 'gui-input',
                                   'fa': 'building-o',
                               }))

    school_name = forms.CharField(
        required=True,
        label='Школа',
        help_text='Например, «Лицей №88»',
        max_length=250,
        widget=TextInputWithFaIcon(attrs={
            'class': 'gui-input',
            'fa': 'graduation-cap',
        }))

    phone = forms.CharField(
        required=True,
        label='Мобильный телефон',
        help_text='Позвоним в экстренной ситуации. Например, +7 900 000 00 00',
        max_length=100,
        widget=TextInputWithFaIcon(
            attrs={
                'placeholder': '+7 900 000 00 00',
                'class': 'gui-input',
                'fa': 'phone',
            }))

    vk = forms.CharField(
        required=True,
        label='Адрес страницы ВКонтакте',
        max_length=100,
        help_text='Адрес страницы ВКонтакте нужен нам для оперативной '
        'и удобной связи с вами. '
        'Если у вас нет страницы, заполните поле прочерком',
        widget=TextInputWithFaIcon(attrs={
            'placeholder': 'vk.com/example',
            'class': 'gui-input',
            'fa': 'vk',
        }))

    telegram = forms.CharField(
        required=False,
        label='Ник в Телеграме',
        max_length=100,
        widget=TextInputWithFaIcon(attrs={
            'placeholder': '@nick',
            'class': 'gui-input',
            'fa': 'paper-plane',
        }))

    codeforces_handle = forms.CharField(
        required=False,
        label=mark_safe(
            'Хэндл на&nbsp;<a href="https://codeforces.com">codeforces.com</a>'
        ),
        max_length=100,
        widget=TextInputWithFaIcon(attrs={
            'placeholder': '',
            'class': 'gui-input',
            'fa': 'user',
        }))

    informatics_username = forms.CharField(
        required=False,
        label=mark_safe(
            'Имя пользователя на&nbsp;<a href="http://informatics.msk.ru">informatics.msk.ru</a>'
        ),
        max_length=100,
        widget=TextInputWithFaIcon(attrs={
            'placeholder': '',
            'class': 'gui-input',
            'fa': 'user',
        }))

    citizenship = EmptyIntChoiceField(
        models.UserProfile.Citizenship.choices,
        label='Гражданство',
        help_text='Выберите «Другое», если имеете несколько гражданств',
        required=False,
    )
    citizenship_other = forms.CharField(
        label='Другое гражданство',
        # TODO hide this field, if citizenship != Citizenship.OTHER
        help_text=
        'Если вы указали «Другое», укажите здесь своё гражданство (или несколько через запятую)',
        required=False,
        max_length=100,
        widget=TextInputWithFaIcon(attrs={
            'class': 'gui-input',
            'fa': 'file-text-o',
        }))

    document_type = EmptyIntChoiceField(
        models.UserProfile.DocumentType.choices,
        label='Документ, удостоверяющий личность',
        required=False,
    )
    document_number = forms.CharField(
        label='Номер документа',
        help_text='Укажите и серию, и номер документа',
        required=False,
        max_length=100,
        widget=TextInputWithFaIcon(attrs={
            'class': 'gui-input',
            'fa': 'file-text-o',
        }))

    t_shirt_size = forms.TypedChoiceField(
        choices=models.UserProfile.TShirtSize.choices,
        required=False,
        label='Размер футболки',
        widget=SistemaRadioSelect(attrs={'inline': True}),
        coerce=int,
        empty_value=None,
    )

    def __init__(self, *args, all_fields_are_required=False, **kwargs):
        if 'initial' in kwargs and 'has_accepted_terms' in kwargs['initial']:
            # As has_accepted_terms is a ChoiceField,
            # its value should be a list, not a bool
            kwargs['initial']['has_accepted_terms'] = \
                [kwargs['initial']['has_accepted_terms']]
        super().__init__(*args, **kwargs)
        if all_fields_are_required:
            for field_name in models.UserProfile.get_fully_filled_field_names(
            ):
                self.fields[field_name].required = True

    def fill_user_profile(self, user):
        if not user.is_authenticated:
            user_profile = models.UserProfile()
        elif hasattr(user, 'profile'):
            user_profile = user.profile
        else:
            user_profile = models.UserProfile(user=user)
        for field_name in user_profile.get_field_names():
            if field_name in self.cleaned_data:
                field_value = self.cleaned_data.get(field_name)
                # has_accepted_terms is a BooleanField in the database, so we need to
                # transform list to bool
                if field_name == 'has_accepted_terms':
                    field_value = field_value[0]
                setattr(user_profile, field_name, field_value)
        return user_profile
Esempio n. 24
0
class ScheduledReportForm(forms.Form):
    config_ids = forms.MultipleChoiceField(
        label="Saved report(s)",
        validators=[MinLengthValidator(1)],
        help_text='Note: not all built-in reports support email delivery, so'
        ' some of your saved reports may not appear in this list')

    interval = forms.TypedChoiceField(label='Interval',
                                      choices=[("daily", "Daily"),
                                               ("weekly", "Weekly"),
                                               ("monthly", "Monthly")])

    day = forms.TypedChoiceField(label="Day",
                                 coerce=int,
                                 required=False,
                                 choices=[(i, i) for i in range(0, 32)])

    hour = forms.TypedChoiceField(label='Time',
                                  coerce=int,
                                  choices=ReportNotification.hour_choices())

    send_to_owner = forms.BooleanField(label='Send to owner', required=False)

    attach_excel = forms.BooleanField(label='Attach Excel Report',
                                      required=False)

    recipient_emails = MultiEmailField(label='Other recipients',
                                       required=False)
    email_subject = forms.CharField(
        required=False,
        help_text=
        'Translated into recipient\'s language if set to "%(default_subject)s".'
        % {
            'default_subject': DEFAULT_REPORT_NOTIF_SUBJECT,
        },
    )

    language = forms.ChoiceField(label='Language',
                                 required=False,
                                 choices=[('', '')] +
                                 langcodes.get_all_langs_for_select(),
                                 widget=forms.Select())

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.form_id = 'id-scheduledReportForm'
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
        self.helper.add_layout(
            crispy.Layout(
                crispy.Fieldset(
                    ugettext("Configure Scheduled Report"), 'config_ids',
                    'interval', 'day', 'hour',
                    B3MultiField(ugettext("Send Options"), 'send_to_owner'),
                    B3MultiField(ugettext("Excel Attachment"), 'attach_excel'),
                    crispy.Field(
                        'email_subject',
                        css_class='input-xlarge',
                    ), 'recipient_emails', 'language',
                    crispy.HTML(
                        render_to_string(
                            'reports/partials/privacy_disclaimer.html'))),
                FormActions(crispy.Submit('submit_btn', 'Submit'))))

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

    def clean(self):
        cleaned_data = super(ScheduledReportForm, self).clean()
        if cleaned_data["interval"] == "daily":
            del cleaned_data["day"]
        _verify_email(cleaned_data)
        return cleaned_data
Esempio n. 25
0
class CrawlForm(forms.Form):
    name_spider = forms.TypedChoiceField(choices=SPIDER_CHOICES)
    url_category = forms.TypedChoiceField(choices=URL_CHOICES)
Esempio n. 26
0
class ExampleForm(forms.Form):
    todo = forms.CharField(
        widget=forms.TextInput(attrs={"class": "form-control"}))
    date = forms.DateField(
        widget=DateTimePicker(options={"format": "YYYY-MM-DD",
                                       "pickTime": False}))
    reminder = forms.DateTimeField(
        required=False,
        widget=DateTimePicker(options={"format": "YYYY-MM-DD HH:mm",
                                       "pickSeconds": False}))

    like_website = forms.TypedChoiceField(
        label = "Do you like this website?",
        choices = ((1, "Yes"), (0, "No")),
        coerce = lambda x: bool(int(x)),
        widget = forms.RadioSelect,
        initial = '1',
        required = True,
    )

    favorite_food = forms.CharField(
        label = "What is your favorite food?",
        max_length = 80,
        required = False,
    )

    favorite_number = forms.IntegerField(
        label = "Favorite number",
        required = False,
    )

    notes = forms.CharField(
        label = "Additional notes or feedback",
        required = False,
    )

    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-exampleForm'
        self.helper.form_class = 'blueForms'
        # self.helper.field_template = 'bootstrap3/layout/inline_field.html'

        self.helper.layout = Layout(
            # InlineField('like_website', readonly=True),
            # 'like_website',
            # CommonLayout,
            'todo',
            'date',
            'reminder',

            InlineField('favorite_food'),
            InlineField('favorite_number'),
            InlineField('notes'),
            Div(
                'favorite_food',
                'favorite_bread',
                css_class='container-fluid'
            ),
            # StrictButton('Sign in', css_class='btn-default'),
        )
        self.helper.form_method = 'post'
        # self.helper.form_action = 'submit_survey'
        self.helper.add_input(Submit('submit', 'Submit'))
Esempio n. 27
0
class PaymentForm(DocumentForm):
    bank_account = forms.ModelChoiceField(
        label=_("Bank Account"), queryset=Account.objects.banks()
    )
    payment = forms.DecimalField(
        localize=True, label=_("Payment"), max_digits=14, decimal_places=4
    )
    discount = forms.TypedChoiceField(
        label=_("Is discounted?"),
        coerce=D,
        choices=[
            ("0.00", _("0%")),
            ("0.01", _("1%")),
            ("0.02", _("2%")),
            ("0.03", _("3%")),
            ("0.04", _("4%")),
            ("0.05", _("5%")),
            ("0.06", _("6%")),
            ("0.07", _("7%")),
        ],
    )

    class Meta(DocumentForm.Meta):
        model = Payment
        fields = ["document_date", "bank_account", "payment", "discount"]
        labels = {"document_date": _("Received Date")}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, formset_class=PaymentFormSet, **kwargs)
        self.payment_value = convert_field_to_value(self["payment"])
        self.calculate_totals(["balance", "split", "discount", "adjustment", "credit"])

    def clean(self):
        splits = Amount.zero()
        for form in self.formset:
            splits += form.split_amount
        if splits.gross != self.payment_value:
            raise forms.ValidationError(
                _("The sum of splits must equal the payment amount.")
            )

    @transaction.atomic
    def save(self, commit=True):

        payment = self.instance
        payment.json = self.json

        if payment.transaction:
            payment.transaction.delete()

        payment.transaction = credit_jobs(
            self.formset.get_transaction_rows(),
            self.cleaned_data["payment"],
            self.cleaned_data["document_date"],
            self.cleaned_data["bank_account"],
        )

        doc_settings = DocumentSettings.get_for_language(get_language())
        payment.letterhead = doc_settings.invoice_letterhead

        pdf_type.payment.serialize(payment)

        invoice = payment.invoice

        if invoice:
            if not invoice.status == Invoice.PAID:
                invoice.pay()
            invoice.set_payment(self.formset.get_json_rows())
            invoice.save()

        super().save(commit)
Esempio n. 28
0
class UserSubmissionForm(forms.ModelForm):
    """Sequence submission form."""

    submittersname = forms.CharField(
        label="Submitter's Name",
        widget=forms.TextInput(attrs={"placeholder": ""}),
    )

    submittersemail = forms.CharField(
        label="Submitter's Email",
        widget=forms.TextInput(attrs={"placeholder": ""}),
    )

    name = forms.CharField(
        label="Your name for the protein",
        widget=forms.TextInput(attrs={"placeholder": ""}),
        required=False,
    )

    year = forms.CharField(
        label="Year",
        widget=forms.TextInput(attrs={"placeholder": ""}),
        required=False,
    )
    sequence = forms.CharField(
        label="Protein Sequence",
        widget=forms.Textarea(attrs={"placeholder": ""}),
        required=True,
    )

    public_or_private = forms.TypedChoiceField(
        label="Do you require the sequence to be maintained privately?",
        coerce=lambda x: x == "True",
        choices=(
            ("", "Select one option"),
            (False, "Yes"),
            (True, "No"),
        ),
        required=True,
    )

    bacterium = forms.ChoiceField(
        choices=((True, "Yes"), (False, "No")),
        label="Bacterium",
        widget=forms.RadioSelect(attrs={"placeholder": ""}),
        initial=True,
        required=False,
    )

    bacterium_textbox = forms.CharField(
        label="Name of source bacterium (ideally taxonid)",
        # label='',
        widget=forms.TextInput(attrs={"placeholder": ""}),
    )

    accession = forms.CharField(
        label="Genbank accession Number",
        widget=forms.TextInput(attrs={"placeholder": ""}),
        required=True,
    )

    dnasequence = forms.CharField(
        label="DNA Sequence",
        widget=forms.Textarea(attrs={"placeholder": ""}),
    )

    partnerprotein = forms.ChoiceField(
        label="Partner Protein required for toxicity?",
        choices=((True, "Yes"), (False, "No")),
        widget=forms.RadioSelect(),
        initial=False,
        required=False,
    )

    partnerprotein_textbox = forms.CharField(
        label="Partner Protein Name",
        widget=forms.TextInput(attrs={"placeholder": ""}),
        required=False,
    )

    toxicto = forms.CharField(
        label="Toxic to",
        widget=forms.TextInput(attrs={"placeholder": ""}),
        required=False,
    )

    nontoxic = forms.CharField(
        label="Nontoxic to",
        widget=forms.TextInput(attrs={"placeholder": ""}),
        required=False,
    )
    pdbcode = forms.CharField(
        label="PDB code",
        widget=forms.TextInput(attrs={"placeholder": ""}),
        required=False,
    )

    publication = forms.CharField(
        label="Publication",
        widget=forms.Textarea(attrs={"placeholder": ""}),
        required=False,
    )

    comment = forms.CharField(
        label="Comments",
        widget=forms.Textarea(attrs={"placeholder": ""}),
        required=False,
    )

    terms_conditions = forms.BooleanField(
        required=True,
        widget=forms.CheckboxInput(attrs={"size": "10"}),
        label=
        "By using our service and submitting your sequences of pesticidal proteins to us, you agree to the following:  You acknowledge that our services are being provided on our regularly operating IT systems, and we cannot guarantee the complete security of your submission.  OUR SERVICE IS PROVIDED “AS IS”.  WE EXPRESSLY DISCLAIM ALL WARRANTIES WITH RESPECT TO THE SERVICES.  WE MAKE NO WARRANTIES OR GUARANTEES WHATSOEVER, EXPRESS OR IMPLIED, INCLUDING, ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  WE ARE NOT LIABLE FOR ANY USE OF THE SERVICES, OR FOR ANY LOSS, CLAIM, DAMAGE, OR LIABILITY OF ANY KIND OR NATURE WHICH MAY ARISE FROM OR IN CONNECTION WITH THIS SERVICE OR OUR STORAGE OF YOUR SUBMISSION.",
    )

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

        self.fields["sequence"].widget.attrs["cols"] = 50
        # self.fields['sequence'].widget.attrs['cols'] = 20
        self.fields["bacterium_textbox"].widget.attrs["cols"] = 10
        self.fields["comment"].widget.attrs["cols"] = 50
        # self.fields['comment'].widget.attrs['cols'] = 20

        self.fields["toxicto"].label = "Toxic to"
        self.helper = FormHelper()
        self.helper.form_id = "id-UserSubmissionForm"
        self.helper.form_class = "UserSubmissionForm"
        self.helper.form_method = "post"
        self.helper.form_action = "submit"
        self.helper.add_input(Submit("submit", "Submit"))

        self.helper.layout = Layout(
            Row(
                Column(
                    "submittersname",
                    css_class="form-group col-md-6 mb-0",
                ),
                Column(
                    "submittersemail",
                    css_class="form-group col-md-6 mb-0",
                ),
                css_class="form-row",
            ),
            Row(
                Column("name", css_class="form-group col-md-10 mb-0"),
                Column("year", css_class="form-group col-md-2 mb-0"),
                css_class="form-row",
            ),
            Row(
                Column("bacterium", css_class="form-group col-md-2 mb-0"),
                Column(
                    "bacterium_textbox",
                    css_class="form-group col-md-6 mb-0",
                ),
                # Column('taxonid',
                #        css_class='form-group col-md-5 mb-0'),
                css_class="form-row",
            ),
            Row(
                Column("accession", css_class="form-group col-md-3 mb-0"),
                css_class="form-row",
            ),
            "dnasequence",
            "sequence",
            "public_or_private",
            Row(
                Column(
                    "partnerprotein",
                    css_class="form-group col-md-3 mb-0",
                ),
                Column(
                    "partnerprotein_textbox",
                    css_class="form-group col-md-9 mb-0",
                ),
                css_class="form-row",
            ),
            "toxicto",
            "nontoxic",
            "pdbcode",
            "publication",
            "comment",
            "terms_conditions",
            HTML(
                '<div class="form-group col-md-6"><div class="g-recaptcha" data-sitekey="%s"></div></div>'
                % RECAPTCHA_PUBLIC_KEY),
            # ButtonHolder(
            #     Submit('submit', 'Submit')
            # )
        )

    def clean_sequence(self):
        sequence_in_form = self.cleaned_data["sequence"]

        # invalidsymbols = invalid_symbol(sequence_in_form)
        if invalidSymbol(sequence_in_form):
            raise forms.ValidationError(
                "There are invalid symbols in the sequence")

        if hasNumbers(sequence_in_form):
            raise forms.ValidationError(
                "There are numbers in the sequence. Please paste protein sequence only"
            )

        if sequence_in_form:
            filename = write_sequence_file(sequence_in_form)
            sequence_is_protein = guess_if_protein(filename)

        if not sequence_in_form:
            raise forms.ValidationError("Please paste valid protein sequences")

        if sequence_is_protein:
            raise forms.ValidationError(
                "Please paste only protein sequences here")
        # print(self.cleaned_data)
        formatted_sequence = textwrap.fill(sequence_in_form, 60)

        return formatted_sequence

    def clean_dnasequence(self):
        dnasequence_in_form = self.cleaned_data["dnasequence"]

        if invalidSymbol(dnasequence_in_form):
            raise forms.ValidationError(
                "There are invalid symbols in the sequence")

        if hasNumbers(dnasequence_in_form):
            raise forms.ValidationError(
                "There are numbers in the sequence. Please paste DNA sequence only"
            )

        if dnasequence_in_form:
            filename = write_sequence_file(dnasequence_in_form)
            sequence_is_dna = guess_if_dna(filename)

        if not dnasequence_in_form:
            raise forms.ValidationError("Please paste valid DNA sequences")

        if sequence_is_dna:
            raise forms.ValidationError("Please paste only DNA sequences here")

        formatted_dnasequence = textwrap.fill(dnasequence_in_form, 60)

        return formatted_dnasequence

    class Meta:
        model = UserSubmission
        fields = [
            "submittersname",
            "submittersemail",
            "name",
            "year",
            "sequence",
            "public_or_private",
            "bacterium",
            "bacterium_textbox",
            "accession",
            "dnasequence",
            "partnerprotein",
            "partnerprotein_textbox",
            "toxicto",
            "nontoxic",
            "pdbcode",
            "publication",
            "comment",
            "terms_conditions",
        ]
Esempio n. 29
0
def get_custom_fields_for_model(content_type, filterable_only=False, bulk_edit=False):
    """
    Retrieve all CustomFields applicable to the given ContentType
    """
    field_dict = OrderedDict()
    custom_fields = CustomField.objects.filter(obj_type=content_type)
    if filterable_only:
        custom_fields = custom_fields.exclude(filter_logic=CF_FILTER_DISABLED)

    for cf in custom_fields:
        field_name = 'cf_{}'.format(str(cf.name))
        initial = cf.default if not bulk_edit else None

        # Integer
        if cf.type == CF_TYPE_INTEGER:
            field = forms.IntegerField(required=cf.required, initial=initial)

        # Boolean
        elif cf.type == CF_TYPE_BOOLEAN:
            choices = (
                (None, '---------'),
                (1, 'True'),
                (0, 'False'),
            )
            if initial is not None and initial.lower() in ['true', 'yes', '1']:
                initial = 1
            elif initial is not None and initial.lower() in ['false', 'no', '0']:
                initial = 0
            else:
                initial = None
            field = forms.NullBooleanField(
                required=cf.required, initial=initial, widget=forms.Select(choices=choices)
            )

        # Date
        elif cf.type == CF_TYPE_DATE:
            field = forms.DateField(required=cf.required, initial=initial, help_text="Date format: YYYY-MM-DD")

        # Select
        elif cf.type == CF_TYPE_SELECT:
            choices = [(cfc.pk, cfc) for cfc in cf.choices.all()]
            if not cf.required or bulk_edit or filterable_only:
                choices = [(None, '---------')] + choices
            # Check for a default choice
            default_choice = None
            if initial:
                try:
                    default_choice = cf.choices.get(value=initial).pk
                except ObjectDoesNotExist:
                    pass
            field = forms.TypedChoiceField(choices=choices, coerce=int, required=cf.required, initial=default_choice)

        # URL
        elif cf.type == CF_TYPE_URL:
            field = LaxURLField(required=cf.required, initial=initial)

        # Text
        else:
            field = forms.CharField(max_length=255, required=cf.required, initial=initial)

        field.model = cf
        field.label = cf.label if cf.label else cf.name.replace('_', ' ').capitalize()
        if cf.description:
            field.help_text = cf.description

        field_dict[field_name] = field

    return field_dict
Esempio n. 30
0
class AppDetailsBasicForm(AppSupportFormMixin, TranslationFormMixin,
                          happyforms.ModelForm):
    """Form for "Details" submission step."""
    PRIVACY_MDN_URL = ('https://developer.mozilla.org/Marketplace/'
                       'Publishing/Policies_and_Guidelines/Privacy_policies')

    PUBLISH_CHOICES = (
        (amo.PUBLISH_IMMEDIATE,
         _lazy(u'Publish my app and make it visible to everyone in the '
               u'Marketplace and include it in search results.')),
        (amo.PUBLISH_PRIVATE,
         _lazy(u'Do not publish my app. Notify me and I will adjust app '
               u'visibility after it is approved.')),
    )

    app_slug = forms.CharField(max_length=30,
                               widget=forms.TextInput(attrs={'class': 'm'}))
    description = TransField(
        label=_lazy(u'Description:'),
        help_text=_lazy(u'This description will appear on the details page.'),
        widget=TransTextarea(attrs={'rows': 4}))
    privacy_policy = TransField(
        label=_lazy(u'Privacy Policy:'),
        widget=TransTextarea(attrs={'rows': 6}),
        help_text=_lazy(
            u'A privacy policy explains how you handle data received '
            u'through your app.  For example: what data do you receive? '
            u'How do you use it? Who do you share it with? Do you '
            u'receive personal information? Do you take steps to make '
            u'it anonymous? What choices do users have to control what '
            u'data you and others receive? Enter your privacy policy '
            u'link or text above.  If you don\'t have a privacy '
            u'policy, <a href="{url}" target="_blank">learn more on how to '
            u'write one.</a>'))
    homepage = TransField.adapt(forms.URLField)(
        label=_lazy(u'Homepage:'),
        required=False,
        widget=TransInput(attrs={'class': 'full'}),
        help_text=_lazy(
            u'If your app has another homepage, enter its address here.'))
    support_url = TransField.adapt(forms.URLField)(
        label=_lazy(u'Website:'),
        required=False,
        widget=TransInput(attrs={'class': 'full'}),
        help_text=_lazy(
            u'If your app has a support website or forum, enter its address '
            u'here.'))
    support_email = TransField.adapt(forms.EmailField)(
        label=_lazy(u'Email:'),
        required=False,
        widget=TransInput(attrs={'class': 'full'}),
        help_text=_lazy(
            u'This email address will be listed publicly on the Marketplace '
            u'and used by end users to contact you with support issues. This '
            u'email address will be listed publicly on your app details page.')
    )
    flash = forms.TypedChoiceField(
        label=_lazy(u'Does your app require Flash support?'),
        required=False,
        coerce=lambda x: bool(int(x)),
        initial=0,
        widget=forms.RadioSelect,
        choices=((1, _lazy(u'Yes')), (0, _lazy(u'No'))))
    notes = forms.CharField(
        label=_lazy(u'Your comments for reviewers'),
        required=False,
        widget=forms.Textarea(attrs={'rows': 2}),
        help_text=_lazy(
            u'Your app will be reviewed by Mozilla before it becomes publicly '
            u'listed on the Marketplace. Enter any special instructions for '
            u'the app reviewers here.'))
    publish_type = forms.TypedChoiceField(
        label=_lazy(u'Once your app is approved, choose a publishing option:'),
        choices=PUBLISH_CHOICES,
        initial=amo.PUBLISH_IMMEDIATE,
        widget=forms.RadioSelect())
    is_offline = forms.BooleanField(
        label=_lazy(u'My app works without an Internet connection.'),
        required=False)

    class Meta:
        model = Webapp
        fields = ('app_slug', 'description', 'privacy_policy', 'homepage',
                  'support_url', 'support_email', 'publish_type', 'is_offline')

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

        # TODO: remove this and put it in the field definition above.
        # See https://bugzilla.mozilla.org/show_bug.cgi?id=1072513
        privacy_field = self.base_fields['privacy_policy']
        privacy_field.help_text = mark_safe(
            privacy_field.help_text.format(url=self.PRIVACY_MDN_URL))

        if 'instance' in kwargs:
            instance = kwargs['instance']
            instance.is_offline = instance.guess_is_offline()

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

    def clean_app_slug(self):
        slug = self.cleaned_data['app_slug']
        slug_validator(slug, lower=False)

        if slug != self.instance.app_slug:
            if Webapp.objects.filter(app_slug=slug).exists():
                raise forms.ValidationError(
                    _('This slug is already in use. Please choose another.'))

            if BlacklistedSlug.blocked(slug):
                raise forms.ValidationError(
                    _('The slug cannot be "%s". Please choose another.' %
                      slug))

        return slug.lower()

    def save(self, *args, **kw):
        if self.data['notes']:
            create_comm_note(self.instance,
                             self.instance.versions.latest(),
                             self.request.user,
                             self.data['notes'],
                             note_type=comm.SUBMISSION)
        self.instance = super(AppDetailsBasicForm, self).save(commit=True)
        uses_flash = self.cleaned_data.get('flash')
        af = self.instance.get_latest_file()
        if af is not None:
            af.update(uses_flash=bool(uses_flash))

        return self.instance