Beispiel #1
0
class CertificateForm(Form):
    """
    Form for importing certificates.
    Validating the certificate by trying to read it with cryptography library.
    """
    certificate = CharField(
        widget=Textarea,
        help_text=_(
            "Certificate in PEM format, WITHOUT -----BEGIN CERTIFICATE----- and "
            "-----END CERTIFICATE-----"))
    signing = BooleanField(
        required=False,
        help_text=_(
            "Use this certificate for signing. If both signing and encryption are "
            "left empty, certificate is used for both."))
    encryption = BooleanField(
        required=False, help_text=_("Use this certificate for encryption"))

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

    def clean(self):
        cleaned_data = super().clean()
        certificate = cleaned_data.get("certificate").replace(
            "-----BEGIN CERTIFICATE-----",
            "").replace("-----END CERTIFICATE-----", "").strip()
        signing = cleaned_data.get("signing")
        encryption = cleaned_data.get("encryption")
        certificate_validator(self.sp, certificate, signing, encryption,
                              ValidationError)
Beispiel #2
0
 def empty_form(self):
     f = self.form(prefix=self.make_prefix("TEMPLATE"))
     f.fields["_exists"] = BooleanField(initial=True, widget=HiddenInput)
     f.fields["_deleted"] = BooleanField(initial=True,
                                         required=False,
                                         widget=SubmitButton)
     return f
  def _construct_forms(self):
    self._construct_mgmt_form()

    self.forms = []
    if not self.is_bound:
      if self.initial is not None:
        for i, data in enumerate(self.initial):
          self.forms.append(self.form(initial=data, prefix=self.make_prefix(i)))
      else:
        self.forms = []
    else:
      for i in range(0, self.management_form.form_counts()):
        # Since the form might be "not valid", you can't use
        # cleaned_data to get at these fields.
        if self.make_prefix(i) + "-_exists" in self.data:
          if self.data.get(self.make_prefix(i) + "-_deleted") != "True":
            f = self.form(data=self.data, prefix=self.make_prefix(i))
            self.forms.append(f)

    if self.management_form.is_valid() and self.management_form.cleaned_data["add"]:
      self.add_form()

    for f in self.forms:
      f.fields["_exists"] = BooleanField(initial=True, widget=HiddenInput)
      # Though _deleted is marked as initial=True, the value is only transmitted
      # if this is the button that's clicked, so the real default is False.
      f.fields["_deleted"] = BooleanField(initial=True, required=False, widget=SubmitButton)
      f.fields["_deleted"].widget.label = "(x)"
Beispiel #4
0
class SubscribeSMSForm(Form):
    stock_out_facilities = BooleanField(
        label=ugettext_lazy("Receive stockout facilities SMS alert"),
        required=False,
        help_text=ugettext_lazy(
            "This will alert you with specific users/facilities that are "
            "stocked out of your commodities"))
    stock_out_commodities = BooleanField(
        label=ugettext_lazy("Receive stockout commodities SMS alert"),
        required=False,
        help_text=ugettext_lazy(
            "This will alert you with specific commodities that are stocked "
            "out by your users/facilities"))
    stock_out_rates = BooleanField(
        label=ugettext_lazy("Receive stockout SMS alert"),
        required=False,
        help_text=ugettext_lazy(
            "This will alert you with the percent of facilities that are "
            "stocked out of a specific commodity"))
    non_report = BooleanField(
        label=ugettext_lazy("Receive non-reporting SMS alert"),
        required=False,
        help_text=ugettext_lazy(
            "This alert highlight users/facilities which have not submitted "
            "their CommCare Supply stock report."))

    def __init__(self, *args, **kwargs):
        super(SubscribeSMSForm, self).__init__(*args, **kwargs)
        self.helper = HQFormHelper()
        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _('Subscribe settings'),
                twbscrispy.PrependedText('stock_out_facilities', ''),
                twbscrispy.PrependedText('stock_out_commodities', ''),
                twbscrispy.PrependedText('stock_out_rates', ''),
                twbscrispy.PrependedText('non_report', '')),
            hqcrispy.FormActions(
                twbscrispy.StrictButton(
                    _("Update settings"),
                    type="submit",
                    css_class="btn-primary",
                ), ))

    def save(self, commtrack_settings):
        alert_config = commtrack_settings.alert_config
        alert_config.stock_out_facilities = self.cleaned_data.get(
            "stock_out_facilities", False)
        alert_config.stock_out_commodities = self.cleaned_data.get(
            "stock_out_commodities", False)
        alert_config.stock_out_rates = self.cleaned_data.get(
            "stock_out_rates", False)
        alert_config.non_report = self.cleaned_data.get("non_report", False)

        commtrack_settings.save()
def toggle_plugin(request):
    """
    activate or deactivate a plugin for this Space
    """
    space = request.SPACE
    if request.method == "POST":
        plugin_name = request.POST['plugin_name'] if 'plugin_name' in \
                    request.POST.keys() else None
        active = request.POST['plugin_active'] if 'plugin_active' in \
                    request.POST.keys() else None
        active = BooleanField(required=False).clean(active)
        if plugin_name and active in (True, False):
            plugin = SpacePluginRegistry().get_plugin(plugin_name)
            model = SpacePluginRegistry().get_instance(plugin_name, space)
            model.active = active
            model.save()
            from django.utils.translation import ugettext_lazy
            if active:
                print(plugin.title, type(plugin.title), dir(plugin.title))
                from django.utils.encoding import force_text
                msg = _("Plugin \"%(title)s\" activated.") % \
                    {'title':plugin.title}
            else:
                msg = _("Plugin \"%(title)s\" deactivated.") % \
                    {'title':plugin.title}
            actstream_action.send(sender=request.user,
                                  verb=_("has been modified"),
                                  action_object=space)
            messages.success(request, msg)
        else:
            messages.error(request, \
                _("You have to provide both a plugin name and new state."))
    else:
        messages.error(request, _("No form data found"))
    return redirect('spaces_settings:settings')
Beispiel #6
0
class UserForm(UserCreationForm):
    ''' Subclass of User Creation Form
        https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.forms.UserCreationForm
    '''

    # Need to override default's UserCreationForm that uses
    # django's User in Meta class.
    # Here we override Meta class with our custom Softhub User
    class Meta:
        model = User
        fields = ("username", )
        # field_classes = {'username': UsernameField}

    developer_check = BooleanField(required=False)

    def save(self, commit=True):
        user = super(UserForm, self).save(commit=True)

        if self.cleaned_data.get('developer_check') is True:
            Developer.objects.create(user_id=user.id)

        # user = super(UserForm, self).save(commit=False)
        # user.set_password(self.cleaned_data["password1"])

        # if commit:
        #     user.save()
        #
        #     if self.cleaned_data.get('developer_check') is True:
        #         Developer.objects.create(user_id=user.id)

        return user
Beispiel #7
0
class JudgingForm(ModelForm):
    class Meta:
        model = JudgeRequestAssigment
        fields = ['score', 'is_passed', 'is_closed']

    is_closed = BooleanField(required=False)

    def save(self, **kwargs):
        instance = super().save(**kwargs)

        is_closed = self.cleaned_data.get('is_closed')
        if instance.judge_request.assignees.filter(
                score__isnull=False).count() > 1:
            is_closed = True
        instance.judge_request.is_closed = is_closed
        instance.judge_request.save()

        attempt, _ = Attempt.objects.get_or_create(
            team=instance.judge_request.team,
            feature=instance.judge_request.feature)
        attempt.score = instance.judge_request.score
        attempt.is_passed = instance.judge_request.is_passed
        print(attempt.is_passed)
        attempt.save()
        return instance
Beispiel #8
0
class Parcel(SoColissimoSchema):
    soap_type_name = "ParcelVO"
    DELIVERY_MODES = ('DOM', 'RDV', 'BPR', 'ACP', 'CDI', 'A2P', 'MRL', 'CIT',
                      'DOS', 'CMT', 'BDP')

    weight = DecimalField(required=True,
                          min_value=0,
                          max_value=30,
                          decimal_places=2)
    DeliveryMode = ChoiceField(required=False,
                               choices=[(d, d) for d in DELIVERY_MODES])
    horsGabarit = BooleanField(required=False)

    insuranceValue = IntegerField(required=False, min_value=0)
    HorsGabaritAmount = IntegerField(required=False, min_value=0)
    Instructions = CharField(required=False)

    def clean_weight(self):
        """Ensure weight does not have a decimal part equals to 00"""
        weight = self.cleaned_data.get('weight')
        if weight % 1 == 0:
            weight = int(weight)
        return weight

    def clean_DeliveryMode(self):
        """ Default to "DOM" delivery mode if not specified """
        delivery_mode = self.cleaned_data.get('delivery_mode')
        if not delivery_mode:
            delivery_mode = "DOM"
        return delivery_mode

    def _set_constants(self, parcel):
        parcel.insuranceRange = "00"
        parcel.ReturnReceipt = False
        parcel.Recommendation = False
Beispiel #9
0
class UserForm(ModelForm):
    """Admin form for :class:`User`."""
    #: Scanlator status.
    is_scanlator = BooleanField(
        label='Scanlator status',
        required=False,
        help_text=('Designates whether the user has '
                   '"groups" and "reader" permissions.'))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['is_scanlator'].initial = \
            'instance' in kwargs and self.instance.is_scanlator

    def save(self, commit: bool = True) -> User:  # pragma: no cover
        is_scanlator = self.cleaned_data.pop('is_scanlator', False)
        instance = super().save(commit=False)
        if is_scanlator and not instance.is_scanlator:
            instance.groups.add(models.Group.objects.get(name='Scanlator'))
            if commit:
                instance.save()
        elif not is_scanlator and instance.is_scanlator:
            instance.groups.remove(models.Group.objects.get(name='Scanlator'))
            if commit:
                instance.save()
        return instance

    class Meta:
        model = User
        fields = '__all__'
Beispiel #10
0
class FormularioLogin(forms.Form):
    """!
    Clase que permite crear el formulario de ingreso a la aplicación

    @author Ing. Leonel P. Hernandez M. (leonelphm at gmail.com)
    @author Ing. Luis Barrios (nikeven at gmail.com)
    @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
    @date 09-01-2017
    @version 1.0.0
    """
    contrasena = CharField()
    usuario = CharField()
    remember_me = BooleanField()

    class Meta:
        fields = ('usuario', 'contrasena', 'remember_me')

    def __init__(self, *args, **kwargs):
        super(FormularioLogin, self).__init__(*args, **kwargs)
        self.fields['contrasena'].widget = PasswordInput()
        self.fields['contrasena'].widget.attrs.update({
            'class':
            'form-control',
            'placeholder':
            'Contraseña'
        })
        self.fields['usuario'].widget.attrs.update({
            'class':
            'form-control',
            'placeholder':
            'Username o Email'
        })
        self.fields['remember_me'].label = "Recordar"
        self.fields['remember_me'].widget = CheckboxInput()
        self.fields['remember_me'].required = False
Beispiel #11
0
def import_common_template(request):
    if not check_white_apps(request):
        return JsonResponse({
            'result':
            False,
            'message':
            'you have no permission to call this api.'
        })

    f = request.FILES.get('data_file', None)
    r = read_template_data_file(f)
    if not r['result']:
        return JsonResponse(r)

    override = BooleanField().to_python(request.POST.get('override', False))

    try:
        import_result = CommonTemplate.objects.import_templates(
            r['data']['template_data'], override)
    except Exception as e:
        logger.exception(e)
        return JsonResponse({
            'result':
            False,
            'message':
            'invalid flow data or error occur, please contact administrator'
        })

    return JsonResponse(import_result)
Beispiel #12
0
class MobileOrganisationCreateForm(CremeModelForm):
    is_favorite = BooleanField(label=pgettext_lazy('mobile-orga',
                                                   'Is favorite'),
                               required=False)

    class Meta:
        model = Organisation
        fields = ('name', 'phone')

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

        # TODO: factorise
        errors = self.errors

        for fname, field in self.fields.items():
            if fname != 'is_favorite':
                attrs = field.widget.attrs
                attrs['class'] = 'form-input' if fname not in errors else \
                                 'form-input form-input-invalid'

                if field.required:
                    attrs['required'] = ''

    def save(self, *args, **kwargs):
        orga = super().save(*args, **kwargs)

        if self.cleaned_data['is_favorite']:
            MobileFavorite.objects.create(entity=orga, user=self.user)

        return orga
    def add_fields(self, form, index):
        super(BaseAnswerFormSet, self).add_fields(form, index)

        try:
            question = form.instance.question
        except Question.DoesNotExist:
            question = Question.objects.get(id=form.initial['question'])

        form.fields['question'].widget = HiddenInput()
        form.fields['project'].widget = HiddenInput()
        form.fields['answer'].widget = self.get_answer_widget(form, question)

        answer = form.initial.get('answer', None)
        if answer == 'No':
            initial = False
        elif answer == None:
            initial = None
        else:
            initial = True

        if question.question_type == question.OPEN_CONDITIONAL:
            form.fields.insert(
                0, 'conditional',
                BooleanField(required=False,
                             widget=RadioSelect(choices=((False, 'No'),
                                                         (True, 'Yes'))),
                             initial=initial))
Beispiel #14
0
class RegForm(forms.Form):
    name = CharField(max_length=30, required=False)
    username = CharField(
        min_length=2,
        max_length=30,
        help_text=
        "30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)",
        widget=TextInput(
            attrs={
                "onfocus": "showRegHelp('username');",
                "onblur": "hideRegHelp('username');return checkUsername();"
            }))
    email = EmailField()
    password = CharField(widget=PasswordInput)
    confirm_password = CharField(widget=PasswordInput)
    next = CharField(widget=HiddenInput(), required=False)
    imghash = CharField(widget=HiddenInput(), required=True)
    imgtext = CharField(
        required=True,
        help_text="Please be case sensitive.  'A' is not the same as 'a'.",
        widget=TextInput(
            attrs={
                "onfocus": "showRegHelp('captcha');",
                "onblur": "hideRegHelp('captcha')"
            }))
    agree_to_terms = BooleanField(required=True)
Beispiel #15
0
class ResetPasswordForm(SetPasswordForm):
    input_field_class = 'border border-gray-400 rounded-full focus:border-blue-500 focus:outline-none w-88 h-10 pl-3'

    new_password1 = CharField(
        label='New password',
        widget=PasswordInput(attrs={
            'autocomplete': 'new-password',
            'class': input_field_class
        }),
        strip=False,
        help_text=password_validation.password_validators_help_text_html(),
    )

    new_password2 = CharField(
        label='New password confirmation',
        strip=False,
        widget=PasswordInput(attrs={
            'autocomplete': 'new-password',
            'class': input_field_class
        }),
    )

    remember = BooleanField(label='Remember me',
                            widget=CheckboxInput(attrs={
                                'checked': 'checked',
                                'class': 'form-checkbox'
                            }))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
class ContainerFormMixin(EntangledModelFormMixin):
    breakpoints = MultipleChoiceField(
        label=_('Available Breakpoints'),
        choices=get_widget_choices(),
        widget=ContainerBreakpointsWidget(choices=get_widget_choices()),
        initial=[
            bp.name for bp in app_settings.CMSPLUGIN_CASCADE['bootstrap4']
            ['fluid_bounds'].keys()
        ],
        help_text=_("Supported display widths for Bootstrap's grid system."),
    )

    fluid = BooleanField(
        label=_('Fluid Container'),
        initial=False,
        required=False,
        help_text=_(
            "Changing your outermost '.container' to '.container-fluid'."))

    class Meta:
        entangled_fields = {'glossary': ['breakpoints', 'fluid']}

    def clean_breapoints(self):
        # TODO: check this
        if len(self.cleaned_data['glossary']['breakpoints']) == 0:
            raise ValidationError(
                _("At least one breakpoint must be selected."))
        return self.cleaned_data['glossary']
Beispiel #17
0
 def __init__(self, *args, **kwargs):
     addition_text = kwargs.pop('addition_text', None)
     addition_js = kwargs.pop('addition_js', '')
     super(BaseDynamicInlineFormSet, self).__init__(*args, **kwargs)
     if not addition_text:
         if len(self.forms):
             addition_text = _('Add another')
         else:
             addition_text = _('Add')
     if self.can_delete:
         dynamic_addition = {}
         form_id = self.management_form.auto_id % self.management_form.prefix
         # Javascript actions
         js_delete = "javascript:{BaseDynamicFormSet.markAsDeleted('%s-%s-', '%s');}"
         js_add = "javascript:{BaseDynamicFormSet.addOther('%s', '%s', '%s', '%s', '%s', '%s');}"
         # Deletion field
         widget = AnchorWidget(attrs={
             'href':
             mark_safe(js_add % (form_id, self.__hash__(), BLANK_FORM,
                                 formsets.INITIAL_FORM_COUNT,
                                 formsets.TOTAL_FORM_COUNT, addition_js))
         },
                               text_shown=addition_text)
         dynamic_addition.update({
             'addition_field':
             widget.render(name="%s-%s" % (self.management_form.prefix,
                                           formsets.DELETION_FIELD_NAME))
         })
         # Add blank form
         blank_widget = widgets.CheckboxInput(
             attrs={
                 'onchange':
                 mark_safe(js_delete % (form_id, BLANK_FORM,
                                        formsets.DELETION_FIELD_NAME))
             })
         blank_field = BooleanField(label=_('Delete'),
                                    required=False,
                                    widget=blank_widget)
         blank_form = self.form(prefix="%s-%s" %
                                (self.management_form.prefix, BLANK_FORM))
         blank_form.fields.update(
             {"%s" % formsets.DELETION_FIELD_NAME: blank_field})
         # Get all as_<tag> methods for forms
         as_methods = [
             m for m in dir(blank_form)
             if (m.startswith('as_') and callable(getattr(blank_form, m)))
         ]
         for as_method in as_methods:
             field_as = forms.CharField(initial=simplejson.dumps(
                 getattr(blank_form, as_method)()),
                                        widget=forms.HiddenInput)
             self.management_form.fields.update(
                 {'%s-%s' % (BLANK_FORM, as_method): field_as})
             self_hash = self.__hash__()
             dynamic_addition[as_method] = mark_safe("""
                 <noscript id="%s"></noscript>
                 <script language="javascript" type="text/javascript">
                 BaseDynamicFormSet.asMethod["%s"] = "%s";
                 </script>""" % (self_hash, self_hash, as_method))
         setattr(self, 'dynamic_addition', dynamic_addition)
Beispiel #18
0
class ManagementForm(forms.Form):
  add = BooleanField(widget=SubmitButton,required=False)
  next_form_id = forms.IntegerField(widget=forms.HiddenInput, initial=0)

  def __init__(self, add_label='+', *args, **kwargs):
    super(ManagementForm, self).__init__(*args, **kwargs)
    self.fields["add"].label = add_label
    self.fields["add"].widget.label = add_label

  def new_form_id(self):
    """
    new_form_id() -> The id for the next member of the formset. Increment hidden value.

    The ManagementForm needs to keep track of a monotonically increasing id, so that
    new member forms don't reuse ids of deleted forms.
    """
    # Hack. self.data is supposed to be immutable.
    res = self.form_counts()
    data2 = self.data.copy()
    data2[self.add_prefix('next_form_id')] = str(res + 1)
    self.data = data2
    return res

  def form_counts(self):
    """form_counts() -> The max number of forms, some could be non-existent (deleted)."""
    try:
      return int(self.data[ self.add_prefix('next_form_id') ])
    except KeyError:
      return self.fields['next_form_id'].initial
def graph_form_factory(model):
    app_name = model._meta.app_label
    model_name = model.__name__

    model_fields = [(f.name, f.verbose_name) for f in model._meta.fields
                    if not f.primary_key]
    graphs = [('PieChart', 'PieChart'), ('BarChart', 'BarChart')]
    model_fields.insert(0, ('', 'N/A'))
    class_name = "%s%sGraphForm" % (app_name, model_name)
    attrs = {
        'initial': {
            'app': app_name,
            'model': model_name
        },
        '_selected_action':
        CharField(widget=MultipleHiddenInput),
        'select_across':
        BooleanField(initial='0', widget=HiddenInput, required=False),
        'app':
        CharField(initial=app_name, widget=HiddenInput),
        'model':
        CharField(initial=model_name, widget=HiddenInput),
        'graph_type':
        ChoiceField(label="Graph type", choices=graphs, required=True),
        'axes_x':
        ChoiceField(label="Group by and count by",
                    choices=model_fields,
                    required=True)
    }

    return DeclarativeFieldsMetaclass(str(class_name), (Form, ), attrs)
Beispiel #20
0
 def add_fields(self, form, index):
     """A hook for adding extra fields on to each form instance."""
     initial_form_count = self.initial_form_count()
     if self.can_order:
         # Only pre-fill the ordering field for initial forms.
         if index is not None and index < initial_form_count:
             form.fields[ORDERING_FIELD_NAME] = IntegerField(
                 label=_("Order"),
                 initial=index + 1,
                 required=False,
                 widget=self.get_ordering_widget(),
             )
         else:
             form.fields[ORDERING_FIELD_NAME] = IntegerField(
                 label=_("Order"),
                 required=False,
                 widget=self.get_ordering_widget(),
             )
     if self.can_delete and (self.can_delete_extra
                             or index < initial_form_count):
         form.fields[DELETION_FIELD_NAME] = BooleanField(
             label=_("Delete"),
             required=False,
             widget=self.get_deletion_widget(),
         )
Beispiel #21
0
class MobileContactCreateForm(MobilePersonCreationFormMixin,
                              quick.ContactQuickForm):
    is_favorite = BooleanField(
        label=pgettext_lazy('mobile-contact', 'Is favorite'), required=False,
    )

    class Meta(quick.ContactQuickForm.Meta):
        fields = ('last_name', 'first_name', 'phone', 'mobile', 'email')
        widgets = {
            'phone':  PhoneInput,
            'mobile': PhoneInput,
        }

    def __init__(self, *args, **kwargs):
        quick.ContactQuickForm.__init__(self, *args, **kwargs)
        MobilePersonCreationFormMixin.__init__(self)

    def clean(self):
        self.cleaned_data['user'] = self.user  # NB: used in super().clean()
        return super().clean()

    def save(self, *args, **kwargs):
        contact = super().save(*args, **kwargs)

        if self.cleaned_data['is_favorite']:
            MobileFavorite.objects.create(entity=contact, user=self.user)

        return contact
Beispiel #22
0
class SnapshotApplicationForm(forms.Form):
    publish = BooleanField(label=ugettext_noop("Publish?"), required=False)
    name = CharField(label=ugettext_noop("Name"), required=True)
    description = CharField(
        label=ugettext_noop("Description"),
        required=False,
        widget=forms.Textarea,
        help_text=ugettext_noop(
            "A detailed technical description of the application"))
    deployment_date = CharField(label=ugettext_noop("Deployment date"),
                                required=False)
    phone_model = CharField(label=ugettext_noop("Phone model"), required=False)
    user_type = CharField(label=ugettext_noop("User type"),
                          required=False,
                          help_text=ugettext_noop("e.g. CHW, ASHA, RA, etc"))
    attribution_notes = CharField(
        label=ugettext_noop("Attribution notes"),
        required=False,
        help_text=ugettext_noop(
            "Enter any special instructions to users here. This will be shown just before users copy your project."
        ),
        widget=forms.Textarea)

    def __init__(self, *args, **kwargs):
        super(SnapshotApplicationForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = [
            'publish', 'name', 'description', 'deployment_date', 'phone_model',
            'user_type', 'attribution_notes'
        ]
class PluginExtraFieldsForm(EntangledModelForm):
    validation_pattern = re.compile(r'^[A-Za-z0-9_-]+$')

    class_names = CharField(
        label=_("CSS class names"),
        required=False,
        widget=widgets.TextInput(attrs={'style': 'width: 50em;'}),
        help_text=
        _("Freely selectable CSS classnames for this Plugin, separated by commas."
          ),
    )

    multiple = BooleanField(
        label=_("Allow multiple"),
        required=False,
        help_text=_("Allow to select multiple of the above CSS classes."),
    )

    class Meta:
        untangled_fields = ['plugin_type', 'site']
        entangled_fields = {
            'css_classes': ['class_names', 'multiple'],
            'inline_styles': [],
        }

    def clean_class_names(self):
        value = self.cleaned_data['class_names']
        for val in value.split(','):
            val = val.strip()
            if val and not self.validation_pattern.match(val):
                msg = _("CSS class '{}' contains invalid characters.")
                raise ValidationError(msg.format(val))
        return value
Beispiel #24
0
class MetadataForm(Form):
    """
    Form for importing metadata.
    """
    metadata = CharField(widget=Textarea,
                         help_text=_("Service Provider metadata"))
    disable_checks = BooleanField(
        required=False, help_text=_("Disable checks for Endpoint bindings"))
    validate = BooleanField(required=False,
                            help_text=_("Validate imported metadata"))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(MetadataForm, self).__init__(*args, **kwargs)
        if not self.user.is_superuser:
            del self.fields['disable_checks']
            del self.fields['validate']

    def clean(self):
        cleaned_data = super().clean()
        metadata = cleaned_data.get("metadata").encode('utf-8')
        parser = etree.XMLParser(ns_clean=True,
                                 remove_comments=True,
                                 remove_blank_text=True,
                                 encoding='utf-8')
        try:
            root = etree.fromstring(metadata, parser)
        except etree.XMLSyntaxError as e:
            raise ValidationError(_("Not valid XML: " + str(e)))
        if etree.QName(root.tag).localname != "EntityDescriptor":
            raise ValidationError(
                _("First element should be EntityDescriptor"))
        entity_id = root.get("entityID")
        if not entity_id:
            raise ValidationError(_("Could not find entityID"))
        if not self.user.is_superuser:
            url_validator = URLValidator()
            try:
                url_validator(entity_id)
            except ValidationError:
                raise ValidationError(
                    _("Entity Id should be URI, please contact IdP admins if "
                      "this is not possible."))
        if ServiceProvider.objects.filter(entity_id=entity_id,
                                          end_at=None,
                                          history=None):
            raise ValidationError(_("Entity Id already exists"))
Beispiel #25
0
class HttpBackendForm(BackendForm):
    url = TrimmedCharField(label=ugettext_noop("URL"), )
    message_param = TrimmedCharField(
        label=ugettext_noop("Message Parameter"), )
    number_param = TrimmedCharField(
        label=ugettext_noop("Phone Number Parameter"), )
    include_plus = BooleanField(
        required=False,
        label=ugettext_noop("Include '+' in Phone Number"),
    )
    method = ChoiceField(
        label=ugettext_noop("HTTP Request Method"),
        choices=(("GET", "GET"), ("POST", "POST")),
    )
    additional_params = RecordListField(
        input_name="additional_params",
        label=ugettext_noop("Additional Parameters"),
    )

    def __init__(self, *args, **kwargs):
        if "initial" in kwargs and "additional_params" in kwargs["initial"]:
            additional_params_dict = kwargs["initial"]["additional_params"]
            kwargs["initial"]["additional_params"] = [{
                "name": key,
                "value": value
            } for key, value in additional_params_dict.items()]
        super(HttpBackendForm, self).__init__(*args, **kwargs)

    def clean_url(self):
        value = self.cleaned_data.get("url")
        if is_url_or_host_banned(value):
            raise ValidationError(_("Invalid URL"))
        return value

    def clean_additional_params(self):
        value = self.cleaned_data.get("additional_params")
        result = {}
        for pair in value:
            name = pair["name"].strip()
            value = pair["value"].strip()
            if name == "" or value == "":
                raise ValidationError("Please enter both name and value.")
            if name in result:
                raise ValidationError("Parameter name entered twice: %s" %
                                      name)
            result[name] = value
        return result

    @property
    def gateway_specific_fields(self):
        return crispy.Fieldset(
            _("HTTP Settings"),
            'url',
            'method',
            'message_param',
            'number_param',
            'include_plus',
            'additional_params',
        )
Beispiel #26
0
class HidePluginFormMixin(EntangledModelFormMixin):
    hide_plugin = BooleanField(
        label=_("Hide plugin"),
        required=False,
        help_text=_("Hide this plugin and all of it's children."))

    class Meta:
        entangled_fields = {'glossary': ['hide_plugin']}
Beispiel #27
0
class PhotoForm(ModelForm):
    image_file = ImageField()

    age_range = ChoiceField(
        choices=Photographer.AGE_RANGE_CHOICES,
        widget=forms.RadioSelect(),
        initial=0,
    )
    gender = ChoiceField(
        choices=Photographer.GENDER_CHOICES,
        widget=forms.RadioSelect(),
        initial=0,
    )
    gender_other = CharField(max_length=20, required=False)

    consent = BooleanField()

    class Meta:
        fields_required = [
            'taken_year',
            'author_focus_keywords',
            'author_reason',
        ]
        model = Photo
        fields = [
            'image_file',
            'taken_year',
            'taken_month',
            'location',
            # TODO: split into three inputs?
            'author_focus_keywords',
            'author_feeling_category',
            'author_feeling_keywords',
            'author_reason',
            # 'photographer__age_range',
            'age_range',
            # 'photographer__gender',
            'gender',
            # 'photographer__gender_other',
            'gender_other',
            'consent',
        ]

        widgets = {
            'location': OSMWidget(dict(
                default_lon=-0.13,
                default_lat=51.5,
            )),
            'author_feeling_category': forms.RadioSelect(),
            # 'taken_month': forms.RadioSelect()
        }

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

        fields_required = getattr(self.Meta, 'fields_required', [])
        for key in fields_required:
            self.fields[key].required = True
Beispiel #28
0
class DomainGlobalSettingsForm(forms.Form):
    default_timezone = TimeZoneChoiceField(
        label=ugettext_noop("Default Timezone"), initial="UTC")

    logo = ImageField(
        label=_("Custom Logo"),
        required=False,
        help_text=_("Upload a custom image to display instead of the "
                    "CommCare HQ logo.  It will be automatically resized to "
                    "a height of 32 pixels."))
    delete_logo = BooleanField(
        label=_("Delete Logo"),
        required=False,
        help_text=_("Delete your custom logo and use the standard one."))

    def __init__(self, *args, **kwargs):
        self.can_use_custom_logo = kwargs.pop('can_use_custom_logo', False)
        super(DomainGlobalSettingsForm, self).__init__(*args, **kwargs)
        if not self.can_use_custom_logo:
            del self.fields['logo']
            del self.fields['delete_logo']

    def clean_default_timezone(self):
        data = self.cleaned_data['default_timezone']
        timezone_field = TimeZoneField()
        timezone_field.run_validators(data)
        return smart_str(data)

    def save(self, request, domain):
        try:
            if self.can_use_custom_logo:
                logo = self.cleaned_data['logo']
                if logo:

                    input_image = Image.open(io.BytesIO(logo.read()))
                    input_image.load()
                    input_image.thumbnail(LOGO_SIZE)
                    # had issues trying to use a BytesIO instead
                    tmpfilename = "/tmp/%s_%s" % (uuid.uuid4(), logo.name)
                    input_image.save(tmpfilename, 'PNG')

                    with open(tmpfilename) as tmpfile:
                        domain.put_attachment(tmpfile, name=LOGO_ATTACHMENT)
                elif self.cleaned_data['delete_logo']:
                    domain.delete_attachment(LOGO_ATTACHMENT)

            global_tz = self.cleaned_data['default_timezone']
            domain.default_timezone = global_tz
            users = WebUser.by_domain(domain.name)
            for user in users:
                dm = user.get_domain_membership(domain.name)
                if not dm.override_global_tz:
                    dm.timezone = global_tz
                    user.save()
            domain.save()
            return True
        except Exception:
            return False
Beispiel #29
0
class LoginForm(forms.Form):
    """!
    Clase del formulario de logeo

    @date 01-03-2017
    @version 1.0.0
    """
    ## Campo de la constraseña
    contrasena = CharField()

    ## Nombre del usuario
    usuario = CharField()

    ## Formulario de recordarme
    remember_me = BooleanField()

    ## Campo del captcha
    #captcha = CaptchaField()

    def __init__(self, *args, **kwargs):
        """!
        Metodo que sobreescribe cuando se inicializa el formulario

        @date 01-03-2017
        @param self <b>{object}</b> Objeto que instancia la clase
        @param args <b>{list}</b> Lista de los argumentos
        @param kwargs <b>{dict}</b> Diccionario con argumentos
        @return Retorna el formulario validado
        """
        super(LoginForm, self).__init__(*args, **kwargs)
        self.fields['contrasena'].widget = PasswordInput()
        self.fields['contrasena'].widget.attrs.update(
            {'placeholder': 'Contraseña'})
        self.fields['usuario'].widget.attrs.update(
            {'placeholder': 'Nombre de Usuario'})
        self.fields['remember_me'].label = "Recordar"
        self.fields['remember_me'].widget = CheckboxInput()
        self.fields['remember_me'].required = False
        #self.fields['captcha'].label = "Captcha"
        #self.fields['captcha'].widget.attrs.update({'class': 'validate'})

    def clean(self):
        """!
        Método que valida si el usuario a autenticar es valido

        @date 21-04-2017
        @param self <b>{object}</b> Objeto que instancia la clase
        @return Retorna el campo con los errores
        """
        usuario = self.cleaned_data['usuario']
        contrasena = self.cleaned_data['contrasena']
        usuario = authenticate(username=usuario, password=contrasena)
        if (not usuario):
            msg = "Verifique su usuario o contraseña"
            self.add_error('usuario', msg)

    class Meta:
        fields = ('usuario', 'contrasena', 'remember_me')
Beispiel #30
0
class LeafletFormMixin(CascadeModelFormMixin):
    map_width = SizeField(
        label=_("Map Width"),
        allowed_units=['px', '%'],
        initial='100%',
        help_text=_(
            "Set the map width in percent relative to containing element."),
    )

    map_height = SizeField(
        label=_("Adapt Map Height"),
        allowed_units=['px', '%'],
        initial='400px',
        help_text=
        _("Set a fixed height in pixels, or percent relative to the map width."
          ),
    )

    map_min_height = SizeField(
        label=_("Adapt Map Minimum Height"),
        allowed_units=['px'],
        required=False,
        help_text=_("Optional, set a minimum height in pixels."),
    )

    scroll_wheel_zoom = BooleanField(
        label=_("Zoom by scrolling wheel"),
        initial=True,
        required=False,
        help_text=_("Zoom into map on mouse over by scrolling wheel."),
    )

    map_position = HiddenDictField(
        initial=app_settings.CMSPLUGIN_CASCADE['leaflet']['default_position'],
    )

    class Meta:
        entangled_fields = {
            'glossary': [
                'map_width', 'map_height', 'map_position', 'map_min_height',
                'scroll_wheel_zoom'
            ]
        }

    def clean(self):
        cleaned_data = super().clean()
        try:
            if isinstance(cleaned_data['map_position'], str):
                cleaned_data['map_position'] = json.loads(
                    cleaned_data['map_position'])
            elif not isinstance(cleaned_data['map_position'], dict):
                raise ValueError
        except (ValueError, KeyError):
            raise ValidationError(
                "Invalid internal position data. Check your Javascript imports."
            )
        return cleaned_data