Exemple #1
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
Exemple #2
0
    def __init__(self, num_inputs=2, value_suffix='', *args, **kwargs):
        """

        :param value_suffix: the suffix to append to the end of the decimal
            field. Default is nothing.
        """
        self.num_inputs = num_inputs
        self.value_suffix = value_suffix
        fields = [DecimalField(required=False)
                  for i in range(num_inputs)]
        widget = self.widget(num_inputs=num_inputs)
        super(MultipleDecimalField, self).__init__(fields=fields,
                                                   widget=widget,
                                                   *args, **kwargs)
Exemple #3
0
 def __init__(self, required=True, fieldsetup_id=None, max_length=None,
              email_label=_('phone number'), send_label=_('send verification code'), code_label=_('verification code'),
              **kwargs):
     self.fieldsetup_id = fieldsetup_id or str(hash(self))
     self.fieldsetup = fieldsetups.setdefault(self.fieldsetup_id, VerifiedPhoneFieldSetup(**kwargs))
     self.widget = VerifiedEmailWidget(
         send_label=send_label,
         fieldsetup_id=self.fieldsetup_id,
         email_attrs={'placeholder': email_label},
         code_attrs={'placeholder': code_label},
     )
     super(VerifiedPhoneField, self).__init__((
         DecimalField(label=email_label, required=required),
         VerificationCodeField(label=code_label, length=self.fieldsetup.code_length),
     ), require_all_fields=False, **kwargs)
Exemple #4
0
class EssayGradeForm(forms.Form):
    """
    A form to validate essaygrade resources
    """
    grader_type = ChoiceField(choices=GRADER_TYPES, required=True)
    feedback = CharField(min_length=0, required=False)
    annotated_text = CharField(min_length=0, required=False)
    success = BooleanField(required=True)
    confidence = DecimalField(required=False, max_value=1, max_digits=10)
    def __init__(self, problem_object = None, **kwargs):
        super(EssayGradeForm, self).__init__(**kwargs)
        self.max_target_scores = None
        if problem_object is not None:
            self.max_target_scores = problem_object.get('max_target_scores',None)

        validator = django_validators.JSONListValidator(matching_list=self.max_target_scores)

        self.fields['target_scores'] = fields.JSONListField(required = True, validators=[validator])
Exemple #5
0
 def __init__(self,
              max_value=None,
              min_value=None,
              max_digits=None,
              decimal_places=None,
              *args,
              **kwargs):
     self.widget = NumberRangeWidget(attrs={'class': 'local-decimal'})
     errors = DecimalField.default_error_messages.copy()
     if 'error_messages' in kwargs:
         errors.update(kwargs['error_messages'])
     localize = kwargs.get('localize', True)
     field = DecimalField(max_value,
                          min_value,
                          max_digits,
                          decimal_places,
                          localize=localize)
     fields = (
         field,
         field,
     )
     super(DecimalRangeField, self).__init__(fields, *args, **kwargs)
Exemple #6
0
class WorkoutFormCreate(ModelForm):
    duration = DecimalField(
        min_value=0,
        max_value=40,
        max_digits=5,
        label="Duration (15 min blocks)",
        help_text="e.g., for a 30 minute workout, enter '2'.")

    with_other_class = BooleanField(
        label="With different class?",
        help_text="BONUS POINTS! Select this if you worked out with" +
        "a teammates from a different graduating class, like a" +
        "Sophomore with a Junior.")

    workout_date = DateField(initial=datetime.today,
                             widget=SelectDateWidget(years=(2015, 2016)),
                             label="Workout Date",
                             help_text="When did you do the workout?")

    activity = ModelChoiceField(
        queryset=Activity.objects.order_by('description'))

    class Meta:
        model = Workout
        fields = [  # Appears in the form in this order:
            'workout_date',
            'activity',
            'with_other_class',
            'duration',
        ]
        exclude = [
            'user',
        ]

    def __init__(self, user=None, *args, **kwargs):
        super(WorkoutFormCreate, self).__init__(*args, **kwargs)
        self._user = user
Exemple #7
0
class DomainInternalForm(forms.Form, SubAreaMixin):
    sf_contract_id = CharField(label=ugettext_noop("Salesforce Contract ID"),
                               required=False)
    sf_account_id = CharField(label=ugettext_noop("Salesforce Account ID"),
                              required=False)
    commcare_edition = ChoiceField(
        label=ugettext_noop("CommCare Plan"),
        initial="community",
        required=False,
        choices=tuple([
            (p, p) for p in
            ["community", "standard", "pro", "advanced", "enterprise"]
        ]))
    services = ChoiceField(label=ugettext_noop("Services"),
                           required=False,
                           choices=tuple_of_copies(
                               ["basic", "plus", "full", "custom"]))
    initiative = forms.MultipleChoiceField(
        label=ugettext_noop("Initiative"),
        widget=forms.CheckboxSelectMultiple(),
        choices=tuple_of_copies(DATA_DICT["initiatives"], blank=False),
        required=False)
    workshop_region = CharField(
        label=ugettext_noop("Workshop Region"),
        required=False,
        help_text=ugettext_noop(
            "e.g. US, LAC, SA, Sub-Saharan Africa, Southeast Asia, etc."))
    project_state = ChoiceField(label=ugettext_noop("Project State"),
                                required=False,
                                choices=tuple_of_copies(
                                    ["POC", "transition", "at-scale"]))
    self_started = ChoiceField(label=ugettext_noop("Self Started?"),
                               choices=tf_choices('Yes', 'No'),
                               required=False)
    area = ChoiceField(label=ugettext_noop("Sector"),
                       required=False,
                       choices=tuple_of_copies(AREA_CHOICES))
    sub_area = ChoiceField(label=ugettext_noop("Sub-Sector"),
                           required=False,
                           choices=tuple_of_copies(SUB_AREA_CHOICES))
    using_adm = ChoiceField(label=ugettext_noop("Using ADM?"),
                            choices=tf_choices('Yes', 'No'),
                            required=False)
    using_call_center = ChoiceField(label=ugettext_noop("Using Call Center?"),
                                    choices=tf_choices('Yes', 'No'),
                                    required=False)
    custom_eula = ChoiceField(label=ugettext_noop("Custom Eula?"),
                              choices=tf_choices('Yes', 'No'),
                              required=False)
    can_use_data = ChoiceField(label=ugettext_noop("Data Usage?"),
                               choices=tf_choices('Yes', 'No'),
                               required=False)
    organization_name = CharField(label=ugettext_noop("Organization Name"),
                                  required=False)
    notes = CharField(label=ugettext_noop("Notes"),
                      required=False,
                      widget=forms.Textarea)
    platform = forms.MultipleChoiceField(label=ugettext_noop("Platform"),
                                         widget=forms.CheckboxSelectMultiple(),
                                         choices=tuple_of_copies(
                                             ["java", "android", "cloudcare"],
                                             blank=False),
                                         required=False)
    phone_model = CharField(label=ugettext_noop("Phone Model"), required=False)
    project_manager = CharField(label=ugettext_noop("Project Manager's Email"),
                                required=False)
    goal_time_period = IntegerField(
        label=ugettext_noop("Goal time period (in days)"), required=False)
    goal_followup_rate = DecimalField(label=ugettext_noop(
        "Goal followup rate (percentage in decimal format. e.g. 70% is .7)"),
                                      required=False)

    def save(self, domain):
        kw = {
            "workshop_region": self.cleaned_data["workshop_region"]
        } if self.cleaned_data["workshop_region"] else {}
        domain.update_internal(
            sf_contract_id=self.cleaned_data['sf_contract_id'],
            sf_account_id=self.cleaned_data['sf_account_id'],
            commcare_edition=self.cleaned_data['commcare_edition'],
            services=self.cleaned_data['services'],
            initiative=self.cleaned_data['initiative'],
            project_state=self.cleaned_data['project_state'],
            self_started=self.cleaned_data['self_started'] == 'true',
            area=self.cleaned_data['area'],
            sub_area=self.cleaned_data['sub_area'],
            using_adm=self.cleaned_data['using_adm'] == 'true',
            using_call_center=self.cleaned_data['using_call_center'] == 'true',
            custom_eula=self.cleaned_data['custom_eula'] == 'true',
            can_use_data=self.cleaned_data['can_use_data'] == 'true',
            organization_name=self.cleaned_data['organization_name'],
            notes=self.cleaned_data['notes'],
            platform=self.cleaned_data['platform'],
            project_manager=self.cleaned_data['project_manager'],
            phone_model=self.cleaned_data['phone_model'],
            goal_time_period=self.cleaned_data['goal_time_period'],
            goal_followup_rate=self.cleaned_data['goal_followup_rate'],
            **kw)
Exemple #8
0
class SendForm(forms.Form):
    email = DecimalField(max_digits=9, decimal_places=0)
Exemple #9
0
class SimpleNotebookSearchForm(forms.Form):
    notebook_type = ChoiceField(choices=[
        (1,
         u'Hogar y Oficina - Revisar correos y Facebook, usar Office, ver videos de Youtube, y correr juegos ligeros.'
         ),
        (2,
         u'Juegos - Correr aplicaciones y juegos 3D pesados (PES, Call of Duty, Battlefield, Starcraft, etc.)'
         ),
        (3,
         u'Netbooks - Pequeños y baratos, para tareas muy básicas de Internet y Office.'
         ),
        (4,
         u'Ultraportátiles - Equipos ligeros de alta autonomía para tareas de hogar y oficina.'
         ),
    ],
                                initial=2)
    max_price = DecimalField(decimal_places=0,
                             widget=HiddenInput,
                             initial=400000)
    store = ModelChoiceField(queryset=Store.objects.all())

    def find_best_notebooks(self):
        max_price = self.cleaned_data['max_price']
        store = self.cleaned_data['store']
        available_entities = StoreHasProductEntity.objects.filter(
            store=store,
            is_available=True,
            shp__isnull=False,
            latest_price__lte=max_price)
        notebook_entity_dict = dict([[e.shp.product.id, e]
                                     for e in available_entities])
        notebooks = Notebook.objects.filter(pk__in=notebook_entity_dict.keys())

        notebook_type = int(self.cleaned_data['notebook_type'])

        if notebook_type == 1:
            # Hogar y oficina
            notebooks = notebooks.filter(
                processor__speed_score__gte=1000,
                ram_quantity__value__gte=2,
                storage_drive__capacity__value__gte=250,
                screen__size__family__base_size__gte=13).order_by(
                    '-processor__speed_score').distinct()
        elif notebook_type == 2:
            # Juegos
            notebooks = notebooks.annotate(
                mvc=Max('video_card__speed_score')).filter(
                    processor__speed_score__gte=2000,
                    ram_quantity__value__gte=3,
                    storage_drive__capacity__value__gte=320,
                    screen__size__family__base_size__gte=14,
                    mvc__gte=4000).order_by('-mvc')
        elif notebook_type == 3:
            # Netbooks
            notebooks = notebooks.filter(
                screen__size__family__base_size=10, ).order_by(
                    '-processor__speed_score').distinct()
        elif notebook_type == 4:
            # Ultraportátiles
            notebooks = notebooks.filter(
                processor__consumption=2,
                screen__size__family__base_size__gte=11,
                screen__size__family__base_size__lte=13,
            ).order_by('-processor__speed_score').distinct()

        entities = [notebook_entity_dict[n.id] for n in notebooks]

        if notebooks:
            return notebooks, entities
        else:
            return [], []