Exemple #1
0
 def test_ESIdentityCardNumberField_invalid_error_override(self):
     # https://github.com/django/django-localflavor/issues/336
     invalid_override_message = 'Please enter a valid number.'
     form = ESIdentityCardNumberField(
         error_messages={'invalid': invalid_override_message})
     self.assertEqual(form.error_messages['invalid'],
                      invalid_override_message)
Exemple #2
0
 def clean(self):
     cleaned_data = super(UsuarioForm, self).clean()
     dni = cleaned_data.get("dni")
     try:
         ESIdentityCardNumberField().clean(dni)
     except forms.ValidationError:
         raise forms.ValidationError("El número identificador (DNI) no es válido")
     p1 = cleaned_data.get('password1')
     p2 = cleaned_data.get('password2')
     if p1 and p2 and p1 != p2:
         raise forms.ValidationError("Las contraseñas deben coincidir")
     return cleaned_data
Exemple #3
0
class ContactForm(forms.Form):
    Nombre = forms.CharField(widget=forms.TextInput())
    Primer_Apellido = forms.CharField(widget=forms.TextInput())
    Segundo_Apellido = forms.CharField(widget=forms.TextInput())
    Fecha_de_Nacimiento = forms.DateField()
    DNI = ESIdentityCardNumberField(max_length=9)
    Provincia = forms.ChoiceField(widget=ESProvinceSelect(),
                                  choices=(('1', 'Almeria'), ('2', 'Cadiz'),
                                           ('3', 'Cordoba'), ('4', 'Granada'),
                                           ('5', 'Huelva'), ('6', 'Jaen'),
                                           ('7', 'Malaga'), ('8', 'Sevilla')))

    Codigo_Postal = ESPostalCodeField(max_length=5)
    Telefono = ESPhoneNumberField(max_length=9)
    Movil = forms.DecimalField(widget=forms.TextInput())
    Email = forms.EmailField(label='Email')
    Estudios_anteriores = forms.CharField(widget=forms.TextInput())
    Observaciones = forms.CharField(widget=forms.TextInput(
        attrs={'size': '70'}))

    def clean(self):
        return self.cleaned_data
Exemple #4
0
class ConsumerForm(forms.ModelForm, BootstrapForm):

    signup_ref = forms.CharField(required=False,
                                 max_length=150,
                                 widget=forms.HiddenInput())
    cif = ESIdentityCardNumberField(label=_('NIF/CIF'))
    iban_code = IBANFormField(
        label=_('Cuenta bancaria (IBAN)'),
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'iban-code',
            'placeholder': 'ES0000000000000000000000'
        }))

    required_fields = [
        'first_name',
        'last_name',
    ]

    class Meta:
        model = Consumer
        exclude = [
            'group', 'status', 'legal_form', 'member_type', 'cr_member',
            'registration_date', 'cyclos_user'
        ]
        widgets = {
            'address': forms.Textarea(attrs={'rows': 3}),
        }

    def save(self, commit=True):

        instance = forms.ModelForm.save(self, False)
        instance.member_type = MEMBER_CONSUMER

        # Do we need to save all changes now?
        if commit:
            instance.save()

        return instance
Exemple #5
0
class ProviderForm(forms.ModelForm, BootstrapForm):

    categories = forms.ModelMultipleChoiceField(
        queryset=Category.objects.filter(), required=False)
    signup_ref = forms.CharField(required=False,
                                 max_length=150,
                                 widget=forms.HiddenInput())
    cif = ESIdentityCardNumberField(label=_('NIF/CIF'))
    iban_code = IBANFormField(
        label=_('Cuenta bancaria (IBAN)'),
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'iban-code',
            'placeholder': 'ES0000000000000000000000'
        }))

    required_fields = [
        'name',
        'business_name',
    ]

    class Meta:
        model = Provider
        exclude = [
            'group', 'status', 'member_type', 'cr_member', 'registration_date',
            'cyclos_user'
        ]

        widgets = {
            'contact_person': forms.TextInput(),
            'address': forms.Textarea(attrs={'rows': 3}),
            'public_address': forms.Textarea(attrs={'rows': 3}),
            'short_description': forms.Textarea(attrs={'rows': 3}),
            'latitude': forms.NumberInput(attrs={'readonly': False}),
            'longitude': forms.NumberInput(attrs={'readonly': False}),
            'networking': forms.Textarea(attrs={'rows': 4}),
            'num_workers_male_partners': forms.NumberInput(attrs={'min': 0}),
            'num_workers_female_partners': forms.NumberInput(attrs={'min': 0}),
            'num_workers_male_non_partners':
            forms.NumberInput(attrs={'min': 0}),
            'num_workers_female_non_partners':
            forms.NumberInput(attrs={'min': 0}),
        }

    # Overriding __init__ here allows us to provide initial data for permissions
    def __init__(self, *args, **kwargs):
        # Only in case we build the form from an instance
        # (otherwise, 'toppings' list should be empty)
        if kwargs.get('instance'):
            initial = kwargs.setdefault('initial', {})
            # The widget for a ModelMultipleChoiceField expects
            # a list of primary key for the selected data.
            initial['categories'] = [
                t.pk for t in kwargs['instance'].categories.all()
            ]

        forms.ModelForm.__init__(self, *args, **kwargs)

    def save(self, commit=True):

        is_new = self.instance.pk is None
        instance = forms.ModelForm.save(self, False)
        instance.member_type = MEMBER_PROV

        if not instance.public_address or instance.public_address == '':
            instance.public_address = instance.address

        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m

        def save_m2m():
            old_save_m2m()
            # This is where we actually link the permissions to the group
            instance.categories.clear()
            instance.categories.add(*self.cleaned_data['categories'])

        self.save_m2m = save_m2m

        # Do we need to save all changes now?
        if commit:
            instance.save()
            self.save_m2m()

        return instance
class ChangeDNIForm(forms.Form):
    _selected_action = forms.CharField(widget=forms.HiddenInput)
    new_dni = ESIdentityCardNumberField(label=_("New DNI"))
Exemple #7
0
 def test_ESIdentityCardNumberField_model_field_default_form(self):
     field = ESIdentityCardNumberModelField()
     self.assertEqual(type(field.formfield()),
                      type(ESIdentityCardNumberField()))
class GenericUserCustomRegistrationFormPromoter(forms.Form):

    email = forms.EmailField(
        max_length=50,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'required': 'true',
            'type': 'email',
        }),
        label='Email')

    phone = ESPhoneNumberField(
        max_length=15,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'required': 'true',
            'type': 'tel',
        }),
        label='Teléfono')

    password1 = forms.CharField(
        max_length=60,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'required': 'true',
            'type': 'password',
        }),
        label='Contraseña')

    password2 = forms.CharField(
        max_length=60,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'required': 'true',
            'type': 'password',
        }),
        label='Repite la contraseña')

    first_name = forms.CharField(max_length=30,
                                 widget=forms.TextInput(attrs={
                                     'class': 'form-control',
                                     'required': 'true'
                                 }),
                                 label='Nombre')

    last_name = forms.CharField(max_length=60,
                                widget=forms.TextInput(attrs={
                                    'class': 'form-control',
                                    'required': 'true'
                                }),
                                label='Apellidos')

    dni = forms.CharField(max_length=10,
                          widget=forms.TextInput(attrs={
                              'class': 'form-control',
                              'required': 'true'
                          }),
                          label='DNI')

    address = forms.CharField(
        max_length=255,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='Dirección')

    postal_code = ESPostalCodeField(
        max_length=10,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
        }),
        label='Código postal')

    city = forms.CharField(max_length=80,
                           widget=forms.TextInput(attrs={
                               'class': 'form-control',
                               'required': 'true'
                           }),
                           label='Ciudad')

    province = forms.CharField(max_length=80,
                               widget=ESProvinceSelect(attrs={
                                   'class': 'form-control',
                               }),
                               label='Provincia')

    promoter_room_or_event_name = forms.CharField(
        max_length=255,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'required': 'true'
        }),
        label='Nombre de la sala o evento')

    promoter_company_name = forms.CharField(
        max_length=255,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
        }),
        label='Razón social')

    promoter_cif = ESIdentityCardNumberField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
        }),
        label='CIF')

    promoter_additional_info = forms.CharField(
        max_length=1000,
        required=False,
        widget=forms.Textarea(attrs={
            'class': 'form-control',
        }),
        label='Provincia')

    newsletter_subscription = forms.BooleanField(initial=True, required=False)

    accept_tos = forms.BooleanField(error_messages={
        'required':
        'Debes aceptar las condiciones de uso para poder registrarte'
    },
                                    label="Acepto las condiciones de uso.")
Exemple #9
0
class ShopForm(forms.ModelForm):
    def clean_photo(self):
        photo = self.cleaned_data['photo']
        if photo is None:
            raise forms.ValidationError("Siusplau, afegeix una fotografia")
        size = getattr(photo, '_size', 0)
        if size > settings.MAX_UPLOAD_SIZE:
            raise forms.ValidationError(
                "Siusplau, la foto ha de tenir un tamany inferior a %s. Actualment %s"
                % (filesizeformat(
                    settings.MAX_UPLOAD_SIZE), filesizeformat(size)))
        return photo

    CIF = ESIdentityCardNumberField(
        only_nif=False,
        label='',
        widget=forms.TextInput(attrs={'placeholder': 'CIF'}))
    secondaryCategories = SelectCategoryField(
        queryset=models.SecondaryCategory.objects.all(),
        placeholder='Busca una categoria ...',
        is_loading=False,
        title="Filtra per categoria:")
    services = SelectCategoryField(queryset=models.Service.objects.all(),
                                   placeholder='Busca un servei ...',
                                   is_loading=False,
                                   title="Filtra per servei:",
                                   required=False)

    meanTime = RangeSliderField(
        label="",
        minimum=0,
        maximum=60,
        step=5,
        name="Quant temps passen els teus usuaris de mitjana?")

    map = LocationField(label='Mapa',
                        map_attrs={
                            "center": [2.1589899, 41.3887901],
                            "marker_color": "#ba6b6c",
                            'zoom': 10,
                            'placeholder': 'Tria una localització a sota'
                        })

    class Meta:
        model = models.Shop
        fields = [
            'CIF', 'name', 'description', 'meanTime', 'services',
            'secondaryCategories', 'photo'
        ]

        labels = {'name': '', 'description': '', 'photo': 'Foto'}

        help_text = {
            'CIF': 'CIF',
            'name': 'Name',
        }

        exclude = ['latitude', 'longitude']

        widgets = {
            'name':
            forms.TextInput(attrs={'placeholder': 'Nom de la botiga'}),
            'description':
            forms.Textarea(attrs={
                'rows': 4,
                'placeholder': 'Descripció'
            }),
            'photo':
            forms.FileInput(),
        }

    def clean(self):
        map = self.cleaned_data['map']
        if map is None:
            raise forms.ValidationError("Necesites unes coordenades")
        elif float(map.split(',')[0]) <= -180 or float(
                map.split(',')[0]) >= 180:
            raise forms.ValidationError("Longitude fora de rang")
        elif float(map.split(',')[1]) < -90 or float(map.split(',')[1]) >= 90:
            raise forms.ValidationError("Latitude fora de rang")
        else:
            pass
        return self.cleaned_data

    def is_add_shop(self):
        return True
Exemple #10
0
class editFicha2(ModelForm):
    dni = ESIdentityCardNumberField(only_nif=True)
    phone = forms.CharField(
        label="Teléfono Móvil",
        validators=[
            validators.RegexValidator(
                regex="^(\d{4})?(-)?\d{3}(-)?\d{3}(-)?\d{3}$",
                message="No es un número de teléfono válido")
        ],
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text="Required")
    photo = forms.ImageField(help_text="Required")

    date = forms.DateField(
        label="Fecha de Nacimiento",
        validators=[
            validators.RegexValidator(
                regex="([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))",
                message="Formato de fecha inválido"),
        ],
        widget=forms.SelectDateWidget(attrs={
            'placeholder': 'AAAA-MM-DD',
            'class': 'form-control'
        },
                                      years=range(1940, year)),
        help_text="Required")
    country = forms.ChoiceField(label="País",
                                choices=Country_choices,
                                widget=forms.Select(attrs={
                                    'class': 'country_form',
                                    'placeholder': 'País'
                                }),
                                help_text="Required")

    weight = forms.IntegerField(
        label="Peso (kg)",
        validators=[
            validators.RegexValidator("[0-9]",
                                      message="Formato erróneo en el peso"),
            validators.MaxValueValidator(limit_value=250,
                                         message="Valor de peso no realista"),
            validators.MinValueValidator(limit_value=20,
                                         message="Valor de peso no realista"),
        ],
        widget=forms.TextInput(attrs={
            'class': 'form_control',
            'placeholder': 'Peso'
        }),
        help_text="Required")

    height = forms.IntegerField(
        label="Altura (cm)",
        validators=[
            validators.RegexValidator("[0-9]",
                                      message="Formato de altura no realista"),
            validators.MaxValueValidator(
                limit_value=250, message="Valor de altura no realista"),
            validators.MinValueValidator(
                limit_value=20, message="Valor de altura no realista"),
        ],
        widget=forms.NumberInput(attrs={
            'class': 'form_control',
            'placeholder': 'Altura'
        }),
        help_text="Required")

    somatotipe = forms.ChoiceField(
        label="Somatotipo",
        choices=somatotipe_choices,
        widget=forms.Select(attrs={'class': 'form_control'}),
        help_text="Required")

    gender = forms.ChoiceField(label="Género",
                               choices=gender_choices,
                               help_text="Required")

    timing = forms.CharField(label="Horarios",
                             widget=forms.Textarea,
                             help_text="Required")
    meals = forms.CharField(label="Comidas",
                            widget=forms.Textarea,
                            help_text="Required")
    sports = forms.CharField(label="Deportes",
                             widget=forms.Textarea,
                             help_text="Required")
    comments = forms.CharField(label="Comentarios Adicionales",
                               widget=forms.Textarea,
                               help_text="Required")
    patologies = forms.CharField(label="Patologías",
                                 widget=forms.Textarea,
                                 help_text="Required")

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

    class Meta:
        model = Record
        fields = [
            'dni', 'phone', 'photo', 'date', 'country', 'weight', 'height',
            'somatotipe', 'gender', 'timing', 'meals', 'patologies', 'sports',
            'comments', 'plan'
        ]