class CoordinatorsContactForm(RepanierForm):
    staff = fields.MultipleChoiceField(
        label=EMPTY_STRING,
        choices=(),
        widget=CheckboxSelectMultipleWidget(
            label=_("This message will only be sent to the member(s) of the management team that you select below:")
        )
    )
    your_email = fields.EmailField(label=_('My email address'))
    subject = fields.CharField(label=_('Subject'), max_length=100)
    message = fields.CharField(label=_('Message'), widget=widgets.Textarea)

    def __init__(self, *args, **kwargs):
        super(CoordinatorsContactForm, self).__init__(*args, **kwargs)
        choices = []
        for staff in Staff.objects.filter(
                is_active=True,
                translations__language_code=translation.get_language()
        ):
            if staff.is_coordinator or staff.is_invoice_manager or staff.is_invoice_referent or staff.is_webmaster:
                r = staff.customer_responsible
                if r is not None:
                    sender_function = staff.safe_translation_getter(
                        'long_name', any_language=True, default=EMPTY_STRING
                    )
                    phone = " ({})".format(r.phone1 if r.phone1 else EMPTY_STRING)
                    name = r.long_basket_name if r.long_basket_name else r.short_basket_name
                    signature = "<b>{}</b> : {}{}".format(sender_function, name, phone)
                    choices.append(("{}".format(staff.id), mark_safe(signature)))
        self.fields["staff"].choices = choices
Exemplo n.º 2
0
class GuestForm(UniqueEmailValidationMixin, DialogModelForm):
    scope_prefix = 'guest'
    form_name = 'customer_form'  # Override form name to reuse template `customer-form.html`
    legend = _("Customer's Data")
    first_name = fields.CharField(label=_("Full Name"))
    # last_name field used instead phonenumber field
    last_name = fields.CharField(label=_("Phone Number"))

    # email = fields.EmailField(label=_("Email address"))

    class Meta:
        # model = get_user_model()  # since we only use the email field, use the User model directly
        model = CustomerModel  # changed by Siarhei
        fields = ['first_name', 'last_name']
        # fields = ['email', 'first_name']

    def __init__(self, initial=None, instance=None, *args, **kwargs):
        if isinstance(instance, CustomerModel):
            instance = instance.user
        super(GuestForm, self).__init__(initial=initial,
                                        instance=instance,
                                        *args,
                                        **kwargs)

    @classmethod
    def form_factory(cls, request, data, cart):
        customer_form = cls(data=data, instance=request.customer.user)
        if customer_form.is_valid():
            request.customer.recognize_as_guest(request, commit=False)
            customer_form.save()
        return customer_form
Exemplo n.º 3
0
class CoordinatorsContactForm(RepanierForm):
    staff = fields.MultipleChoiceField(label=EMPTY_STRING,
                                       choices=[],
                                       widget=CheckboxSelectMultipleWidget())
    your_email = fields.EmailField(label=_('Your Email'))
    subject = fields.CharField(label=_('Subject'), max_length=100)
    message = fields.CharField(label=_('Message'), widget=widgets.Textarea)

    def __init__(self, *args, **kwargs):
        super(CoordinatorsContactForm, self).__init__(*args, **kwargs)
        choices = []
        for staff in Staff.objects.filter(
                is_active=True,
                is_contributor=False,
                translations__language_code=translation.get_language()):
            r = staff.customer_responsible
            if r is not None:
                sender_function = staff.safe_translation_getter(
                    'long_name', any_language=True, default=EMPTY_STRING)
                phone = " (%s)" % r.phone1 if r.phone1 else EMPTY_STRING
                name = r.long_basket_name if r.long_basket_name else r.short_basket_name
                signature = "<b>%s</b> : %s%s" % (sender_function, name, phone)
                choices.append(("%d" % staff.id, mark_safe(signature)))
        self.fields["staff"] = fields.MultipleChoiceField(
            label=EMPTY_STRING,
            choices=choices,
            widget=CheckboxSelectMultipleWidget())
Exemplo n.º 4
0
class CustomerForm(DialogModelForm):
    scope_prefix = 'customer'
    legend = _("Customer's Details")

    email = fields.EmailField(label=_("Email address"))
    first_name = fields.CharField(label=_("First Name"))
    last_name = fields.CharField(label=_("Last Name"))

    class Meta:
        model = CustomerModel
        exclude = ['user', 'recognized', 'number', 'last_access']
        custom_fields = ['email', 'first_name', 'last_name']

    def __init__(self, initial=None, instance=None, *args, **kwargs):
        initial = dict(initial) if initial else {}
        assert instance is not None
        initial.update(dict((f, getattr(instance, f)) for f in self.Meta.custom_fields))
        super().__init__(initial=initial, instance=instance, *args, **kwargs)

    @property
    def media(self):
        return Media(css={'all': [sass_processor('shop/css/customer.scss')]})

    def save(self, commit=True):
        for f in self.Meta.custom_fields:
            setattr(self.instance, f, self.cleaned_data[f])
        return super().save(commit)

    @classmethod
    def form_factory(cls, request, data, cart):
        customer_form = cls(data=data, instance=request.customer)
        if customer_form.is_valid():
            customer_form.instance.recognize_as_registered(request, commit=False)
            customer_form.save()
        return customer_form
Exemplo n.º 5
0
class ContainerForm(Bootstrap3FormMixin, NgModelFormMixin,
                    NgFormValidationMixin, NgModelForm):
    scope_prefix = 'container'
    form_name = 'container_form'
    location = ngfields.ModelChoiceField(
        label="Location (SDS § 7)",
        queryset=models.Location.objects.order_by('name'))
    date_opened = ngfields.DateField(widget=DateInput(), required=False)
    expiration_date = ngfields.DateField(widget=DateInput())
    state = ngfields.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'Solid, liquid, foil, etc.'}))
    unit_of_measure = ngfields.CharField(
        widget=forms.TextInput(attrs={'placeholder': 'g, mL, etc'}),
        required=False)
    batch = ngfields.CharField(label='Batch/Lot Number', required=False)
    container_type = ngfields.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'Glass bottle, metal pouch, etc.'}))

    class Meta:
        model = models.Container
        fields = [
            'location', 'batch', 'date_opened', 'expiration_date', 'state',
            'container_type', 'quantity', 'unit_of_measure', 'supplier',
            'comment'
        ]
Exemplo n.º 6
0
class MembersContactForm(RepanierForm):
    recipient = fields.CharField(label=_('Recipient(s)'))
    your_email = fields.EmailField(label=_('Your Email'))
    subject = fields.CharField(label=_('Subject'), max_length=100)
    message = fields.CharField(label=_('Message'), widget=widgets.Textarea)

    def __init__(self, *args, **kwargs):
        super(MembersContactForm, self).__init__(*args, **kwargs)
Exemplo n.º 7
0
class CustomArgsForm(forms.Form):
    field1 = fields.CharField(widget=widgets.HiddenInput)
    field2 = fields.CharField(widget=widgets.HiddenInput)

    def __init__(self, custom_arg1=None, custom_arg2=None, *args, **kwargs):
        self.custom_arg1 = custom_arg1
        self.custom_arg2 = custom_arg2
        super(CustomArgsForm, self).__init__(*args, **kwargs)
Exemplo n.º 8
0
class EditOrderForm(Bootstrap3Form):

    status = fields.ChoiceField(choices=Order.status_in_choices, label='Статус',
                                widget=forms.RadioSelect, required=True)
    prepay = fields.FloatField(label='Сумма предоплаты', required=True)
    relay_free = fields.FloatField(label='Сумма оплаты за пересылку')
    total = fields.FloatField(label='Итоговая сумма', required=True)
    type_of_dispatch = fields.ChoiceField(choices=Order.dispatch, label='Тип отправления', widget=forms.Select, required=True)
    track_number = fields.CharField(label='Номер для отслеживания',  min_length=0, max_length=20, required=False)
    linked_orders = fields.CharField(label='Связанные заказы', min_length=0, max_length=100, required=False)
Exemplo n.º 9
0
class DialogModelForm(DialogFormMixin, Bootstrap3ModelForm):
    """
    Base class for all dialog model forms used with a DialogFormPlugin.
    """
    plugin_id = fields.CharField(
        widget=widgets.HiddenInput,
        required=False,
    )

    plugin_order = fields.CharField(widget=widgets.HiddenInput)
Exemplo n.º 10
0
class MembersContactForm(RepanierForm):
    recipient = fields.CharField(
        label=_('Recipient(s)'),
        initial=_("All members who agree to receive mails from this site"))
    your_email = fields.EmailField(label=_('My email address'))
    subject = fields.CharField(label=_('Subject'), max_length=100)
    message = fields.CharField(label=_('Message'), widget=widgets.Textarea)

    def __init__(self, *args, **kwargs):
        super(MembersContactForm, self).__init__(*args, **kwargs)
Exemplo n.º 11
0
class SearchForm_(Bootstrap3Form):

    BASE_CHOICES = [('egrul', 'ЕГРЮЛ'), ('egrip', 'ЕГРИП')]

    ACTIVE_CHOICES = [
        ('', 'Все'),
        ('False', 'Деятельность юридического лица прекращена'),
        ('True',
         'Действующее юридическое лицо или код статуса юридического лица по справочнику СЮЛСТ больше 200 и меньше 700'
         ),
    ]

    # base = fields.ChoiceField(label='Выберите реестр', initial='egrul', choices=BASE_CHOICES)
    search = fields.CharField(
        min_length=2,
        label='ОГРН, ИНН или наименование юридического лица',
        required=True,
        error_messages={
            "invalid": "Доложно быть заполнено, минимум 2 символа"
        })
    fio = fields.CharField(
        min_length=2,
        label=
        'ФИО лица, являющегося руководителем, учредителем или участником ЮЛ',
        required=False,
        error_messages={
            "invalid": "Доложно быть заполнено, минимум 2 символа"
        })
    reg_start_date = fields.DateField(label='Дата начала постановки на учет:',
                                      required=False,
                                      input_formats=['%Y-%m-%d'])
    reg_end_date = fields.DateField(label='Дата окончания постановки на учет:',
                                    required=False,
                                    input_formats=['%Y-%m-%d'])
    #region = fields.ChoiceField(initial='', label='Регион', choices=REGION_CHOICES)
    region = fields.ModelChoiceField(empty_label='Любой',
                                     label='Регион',
                                     to_field_name='КодРегион',
                                     queryset=Regions.objects.all())
    isactive = fields.ChoiceField(initial='',
                                  label='Прекращение деятельности',
                                  choices=ACTIVE_CHOICES)
    #state = fields.ChoiceField(initial='', label='Cостояние (статус) юридического лица', choices=STATE_CHOICES)
    state = fields.ModelChoiceField(
        empty_label='Любое',
        label='Cостояние (статус) юридического лица',
        to_field_name='КодСтатусЮЛ',
        queryset=States.objects.all())
    okved = fields.ModelChoiceField(
        empty_label='Любое',
        label='Наименование вида деятельности по ОКВЭД',
        to_field_name='КодОКВЭД',
        queryset=OKVED.objects.all())
Exemplo n.º 12
0
class DialogForm(DialogFormMixin, Bootstrap3Form):
    """
    Base class for all dialog forms used with a DialogFormPlugin.
    """
    label_css_classes = 'control-label font-weight-bold'

    plugin_id = fields.CharField(
        widget=widgets.HiddenInput,
        required=False,
    )

    plugin_order = fields.CharField(widget=widgets.HiddenInput, )
Exemplo n.º 13
0
class LoginForm_(Bootstrap3Form):

    login = fields.CharField(
        label='Логин',
        min_length=2,
        max_length=20,
        required=True,
        error_messages={
            'invalid':
            'Поле должно быть заполнено. Минимум 2 символа, максимум 20'
        })
    password = fields.CharField(label='Пароль',
                                widget=forms.PasswordInput,
                                required=True)
Exemplo n.º 14
0
class DummyForm(NgModelFormMixin, NgForm):
    email = fields.EmailField(label='E-Mail')
    onoff = fields.BooleanField(initial=False, required=True)
    sex = fields.ChoiceField(choices=(('m', 'Male'), ('f', 'Female')),
                             widget=widgets.RadioSelect)
    select_multi = fields.MultipleChoiceField(choices=CHOICES)
    check_multi = fields.MultipleChoiceField(
        choices=CHOICES, widget=widgets.CheckboxSelectMultiple)
    hide_me = fields.CharField(widget=widgets.HiddenInput)
    scope_prefix = 'dataroot'

    def __init__(self, *args, **kwargs):
        kwargs.update(auto_id=False,
                      ng_class='fieldClass(\'%(identifier)s\')',
                      scope_prefix=self.scope_prefix)
        super(DummyForm, self).__init__(*args, **kwargs)
        self.sub1 = SubForm1(prefix='sub1', **kwargs)
        self.sub2 = SubForm2(prefix='sub2', **kwargs)

    def get_initial_data(self):
        data = super(DummyForm, self).get_initial_data()
        data.update({
            self.sub1.prefix: self.sub1.get_initial_data(),
            self.sub2.prefix: self.sub2.get_initial_data(),
        })
        return data

    def is_valid(self):
        if not self.sub1.is_valid():
            self.errors.update(self.sub1.errors)
        if not self.sub2.is_valid():
            self.errors.update(self.sub2.errors)
        return super(
            DummyForm,
            self).is_valid() and self.sub1.is_valid() and self.sub2.is_valid()
Exemplo n.º 15
0
class CommentForm(Bootstrap3Form):
    comment = fields.CharField(label='Комментарий к заказу',
                               required=False,
                               widget=forms.Textarea(attrs={
                                   'cols': '80',
                                   'rows': '5'
                               }))
Exemplo n.º 16
0
class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3Form):
    scope_prefix = 'subscribe_data'
    form_name = 'my_form'
    use_required_attribute = False

    full_name = fields.CharField(
        label='Full name',
        min_length=3,
        max_length=99,
        required=True,
    )

    avatar = fields.ImageField(
        label='Photo of yourself',
        required=True,
    )

    permit = fields.FileField(
        label='Your permit as PDF',
        accept='application/pdf',
        required=False,
    )

    def clean_avatar(self):
        """
        For instance, here you can move the temporary file stored in
        `self.cleaned_data['avatar'].file` to a permanent location.
        """
        self.cleaned_data['avatar'].file
Exemplo n.º 17
0
class ChemicalForm(NgModelFormMixin, NgFormValidationMixin,
                   Bootstrap3FormMixin, NgModelForm):
    # class ChemicalForm(forms.ModelForm):
    scope_prefix = 'chemical'
    form_name = 'chemical_form'
    cas_number = ngfields.CharField(
        label="CAS Number (SDS § 1)",
        required=False,
        widget=forms.TextInput(attrs={'placeholder': 'eg. 7732-18-5'}))
    formula = ngfields.CharField(
        label="Formula (SDS § 3)",
        required=False,
        # widget=forms.TextInput(attrs={'placeholder': 'eg. H_2O', 'ow-formula': 'ow-formula'})
    )
    ghs_hazards = ngfields.ModelMultipleChoiceField(
        label="GHS Hazards (SDS § 2)",
        # widget=forms.SelectMultiple(attrs={'ow-form': 'chemical_form'}),
        queryset=models.Hazard.objects.all(),
        required=False)
    health = ngfields.ChoiceField(label="Health NFPA Rating (SDS § 15 or 16)",
                                  choices=NFPA_RATINGS)
    flammability = ngfields.ChoiceField(
        label="Flammability NFPA Rating (SDS § 15 or 16)",
        choices=NFPA_RATINGS)
    instability = ngfields.ChoiceField(
        label="Instability NFPA Rating (SDS § 15 or 16)", choices=NFPA_RATINGS)
    special_hazards = ngfields.ChoiceField(
        label="Special Hazards (SDS § 15 or 16)",
        choices=NFPA_HAZARDS,
        required=False)
    gloves = ngfields.ModelMultipleChoiceField(
        label="Gloves (SDS § 8.2)", queryset=models.Glove.objects.all())
    safety_data_sheet = ngfields.FileField(
        label="Safety Data Sheet (MSDS)",
        widget=forms.FileInput(
            attrs={'file-model': 'chemical.safety_data_sheet'}),
        required=False)

    class Meta:
        model = models.Chemical
        fields = [
            'name', 'cas_number', 'formula', 'ghs_hazards', 'health',
            'flammability', 'instability', 'special_hazards', 'gloves',
            'safety_data_sheet'
        ]
Exemplo n.º 18
0
class CustomerForm(RepanierForm):
    long_basket_name = fields.CharField(label=_("Your name"), max_length=100)

    email1 = fields.EmailField(
        label=_('Your main email, used for password recovery and login'))
    email2 = fields.EmailField(label=_('Your secondary email'), required=False)
    accept_mails_from_members = fields.BooleanField(label=EMPTY_STRING,
                                                    required=False)
    subscribe_to_email = fields.BooleanField(label=EMPTY_STRING,
                                             required=False)

    phone1 = fields.CharField(label=_('Your main phone'), max_length=25)
    phone2 = fields.CharField(label=_('Your secondary phone'),
                              max_length=25,
                              required=False)

    accept_phone_call_from_members = fields.BooleanField(label=EMPTY_STRING,
                                                         required=False)
    city = fields.CharField(label=_('Your city'),
                            max_length=50,
                            required=False)
    address = fields.CharField(label=_('address'),
                               widget=widgets.Textarea(attrs={
                                   'cols': '40',
                                   'rows': '3'
                               }),
                               required=False)
    picture = fields.CharField(label=_("picture"),
                               widget=AjaxPictureWidget(upload_to="customer",
                                                        size=SIZE_S,
                                                        bootstrap=True),
                               required=False)

    about_me = fields.CharField(label=_('About me'),
                                widget=widgets.Textarea(attrs={
                                    'cols': '40',
                                    'rows': '3'
                                }),
                                required=False)

    def clean_email1(self):
        email1 = self.cleaned_data["email1"]
        user_model = get_user_model()
        qs = user_model.objects.filter(
            email=email1,
            is_staff=False).exclude(id=self.request.user.id).order_by('?')
        if qs.exists():
            self.add_error('email1',
                           _('The given email is used by another user'))
        return email1

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(CustomerForm, self).__init__(*args, **kwargs)
        self.fields["accept_mails_from_members"].widget = CheckboxWidget(
            label=_('My emails are visible to all members'))
        self.fields["accept_phone_call_from_members"].widget = CheckboxWidget(
            label=_('My phones numbers are visible to all members'))
        self.fields["subscribe_to_email"].widget = CheckboxWidget(
            label=_('I subscribe to emails send by repanier'))
Exemplo n.º 19
0
class CustomerForm(RepanierForm):
    long_basket_name = fields.CharField(label=_("My name is"), max_length=100)
    zero_waste = fields.BooleanField(
        label=EMPTY_STRING, required=False
    )
    email1 = fields.EmailField(label=_('My main email address, used to reset the password and connect to the site'))
    email2 = fields.EmailField(label=_('My secondary email address (does not allow to connect to the site)'),
                               required=False)
    show_mails_to_members = fields.BooleanField(
        label=EMPTY_STRING, required=False
    )
    subscribe_to_email = fields.BooleanField(
        label=EMPTY_STRING, required=False
    )

    phone1 = fields.CharField(label=_('My main phone number'), max_length=25)
    phone2 = fields.CharField(label=_('My secondary phone number'), max_length=25, required=False)
    show_phones_to_members = fields.BooleanField(
        label=EMPTY_STRING, required=False
    )
    city = fields.CharField(label=_('My city'), max_length=50, required=False)
    address = fields.CharField(label=_('My address'), widget=widgets.Textarea(attrs={'cols': '40', 'rows': '3'}),
                               required=False)
    picture = fields.CharField(
        label=_("My picture"),
        widget=AjaxPictureWidget(upload_to="customer", size=SIZE_S, bootstrap=True),
        required=False)

    about_me = fields.CharField(label=_('About me'), widget=widgets.Textarea(attrs={'cols': '40', 'rows': '3'}),
                                required=False)

    def clean_email1(self):
        email1 = self.cleaned_data["email1"]
        user_model = get_user_model()
        qs = user_model.objects.filter(
            email=email1, is_staff=False
        ).exclude(
            id=self.request.user.id
        ).order_by('?')
        if qs.exists():
            self.add_error('email1', _('The email {} is already used by another user.').format(email1))
        return email1

    def __init__(self, *args, **kwargs):
        from repanier.apps import REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO

        self.request = kwargs.pop('request', None)
        super(CustomerForm, self).__init__(*args, **kwargs)
        if REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO:
            self.fields["show_mails_to_members"].widget = CheckboxWidget(
                label=_("I agree to show my email addresses in the \"who's who\""))
            self.fields["show_phones_to_members"].widget = CheckboxWidget(
                label=_("I agree to show my phone numbers in the \"who's who\""))
        else:
            self.fields["show_mails_to_members"].widget = HiddenInput()
            self.fields["show_phones_to_members"].widget = HiddenInput()
        self.fields["subscribe_to_email"].widget = CheckboxWidget(
            label=_('I agree to receive unsolicited mails from this site'))
        self.fields["zero_waste"].widget = CheckboxWidget(
            label=_('Family zero waste'))
Exemplo n.º 20
0
class InputForm_(Bootstrap3Form):

    search = fields.CharField(
        min_length=2,
        label=
        'Для поиска необходимо ввести ОГРН или ИНН юридического лица либо указать наименование',
        required=True,
        error_messages={
            "invalid": "Доложно быть заполнено, минимум 2 символа"
        })
Exemplo n.º 21
0
class DialogModelForm(DialogFormMixin, Bootstrap3ModelForm):
    """
    Base class for all dialog model forms used with a DialogFormPlugin.
    """
    plugin_id = fields.CharField(
        widget=widgets.HiddenInput,
        required=False,
    )

    plugin_order = fields.CharField(widget=widgets.HiddenInput)

    @cached_property
    def field_css_classes(self):
        css_classes = {'*': getattr(Bootstrap3ModelForm, 'field_css_classes')}
        for name, field in self.fields.items():
            if not field.widget.is_hidden:
                css_classes[name] = [css_classes['*']]
                css_classes[name].append('{}-{}'.format(self.scope_prefix, name))
        return css_classes
Exemplo n.º 22
0
class NotLoginForm_(Bootstrap3Form):

    firstname = fields.CharField(
        label='Имя',
        min_length=2,
        max_length=100,
        required=True,
        error_messages={'invalid': 'Минимум 2 символа'})
    lastname = fields.CharField(
        label='Фамилия',
        min_length=2,
        max_length=100,
        required=True,
        error_messages={'invalid': 'Минимум 2 символа'})
    middlename = fields.CharField(
        label='Отчество',
        min_length=2,
        max_length=100,
        required=True,
        error_messages={'invalid': 'Минимум 2 символа'})
    email = fields.EmailField(
        label='E-Mail',
        required=True,
        error_messages={'invalid': '*****@*****.**'},
        help_text='Информация о  заказе будет выслана на указанный Вами e-mail'
    )
    address = fields.CharField(label='Адрес',
                               required=True,
                               widget=forms.Textarea(attrs={
                                   'cols': '80',
                                   'rows': '3'
                               }))
    tel = fields.RegexField(
        r'^\+?[0-9 .-]{4,25}$',
        label='Телефон',
        error_messages={'invalid': '4-25 цифр, начинается с \'+\''})

    comment = fields.CharField(label='Комментарий к заказу',
                               required=False,
                               widget=forms.Textarea(attrs={
                                   'cols': '80',
                                   'rows': '5'
                               }))
Exemplo n.º 23
0
class RestoreForm_(Bootstrap3Form):

    login = fields.CharField(
        label='Логин',
        min_length=2,
        max_length=20,
        required=True,
        help_text='Введите ваш логин. '
        'На адрес электронной почты, указанной в параметрах вашей учетной записи, будет отправлено письмо с инструкция по восстановлению пароля. '
        'Если вы не получите отправленное письмо или забыли свой логин, пожалуйста, свяжитесь с администрацией сайта.'
    )
Exemplo n.º 24
0
class SupportingDocumentForm(NgModelFormMixin, NgFormValidationMixin,
                             Bootstrap3FormMixin, NgModelForm):
    form_name = 'supporting_document_form'
    comment = ngfields.CharField(required=False,
                                 widget=forms.Textarea(attrs={'rows': '3'}))
    file = ngfields.FileField(label="Document file",
                              fileupload_url=reverse_lazy('fileupload'),
                              required=True)

    class Meta:
        model = models.SupportingDocument
        fields = ['name', 'file', 'comment']
Exemplo n.º 25
0
class SearchForm(Bootstrap3Form):
    """This object is representing a form used for searchng through searchplaces"""
    search_places = SearchPlace.objects.values('id', 'name')
    search_string = fields.CharField(label="Search", max_length=100)
    search_on = fields.MultipleChoiceField(choices=[])

    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)
        self.fields['search_on'] = fields.MultipleChoiceField(
            label="Search On",
            widget=forms.CheckboxSelectMultiple,
            choices=[(place.id, place.name)
                     for place in SearchPlace.objects.all()])
Exemplo n.º 26
0
class GetOrderingForm_(Bootstrap3Form):

    TYPES_CHOICES = [('fo', 'Получение выписки, содержащей открытые сведения'),
                     ('fz', 'Получение выписки, содержащей закрытые сведения')]

    type = fields.ChoiceField(initial='fz',
                              label='Выберите тип запроса',
                              choices=TYPES_CHOICES)

    search = fields.CharField(
        min_length=13,
        label='ОГРН юридического лица',
        required=True,
        error_messages={"invalid": "Параметр не является ОГРН"})
Exemplo n.º 27
0
class ExtraAnnotationForm(DialogForm):
    scope_prefix = 'data.extra_annotation'

    annotation = fields.CharField(
        label=_("Extra annotation for this order"),
        required=False,
        widget=widgets.Textarea,
    )

    @classmethod
    def form_factory(cls, request, data, cart):
        extra_annotation_form = cls(data=data)
        if extra_annotation_form.is_valid():
            cart.extra.update(extra_annotation_form.cleaned_data)
        return extra_annotation_form
Exemplo n.º 28
0
class ContactUsForm(NgModelFormMixin, Bootstrap3Form):
    '''
    Form for contacting us
    '''
    form_name = 'contact_us_form'
    scope_prefix = 'contact_us'
    field_css_classes = 'input-group has-feedback'

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

    email = fields.EmailField(
        label=_("Your e-mail address"),
        widget=EmailInput(attrs={'placeholder': _("E-mail address")}))

    subject = fields.CharField(
        label=_("Subject"),
        max_length=256,
        widget=TextInput(attrs={'placeholder': _("Subject")}))

    body = fields.CharField(label=_("Text"),
                            widget=Textarea(attrs={'required': True}))

    def save(self, request=None):
        '''
        send mail and so
        '''
        email = self.cleaned_data['email']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        mail.send(settings.WELTLADEN_EMAIL_ADDRESS,
                  email,
                  subject=subject,
                  message=body)
        email_queued()
Exemplo n.º 29
0
class ReorderButtonForm(ShopOrderViewsForm):
    button_content = fields.CharField(required=False, label=_("Button Content"),
                                      widget=widgets.TextInput())

    def __init__(self, raw_data=None, *args, **kwargs):
        instance = kwargs.get('instance')
        if instance:
            initial = {'button_content': instance.glossary.get('button_content') }
            kwargs.update(initial=initial)
        super(ReorderButtonForm, self).__init__(raw_data, *args, **kwargs)

    def clean(self):
        cleaned_data = super(ReorderButtonForm, self).clean()
        if self.is_valid():
            cleaned_data['glossary']['button_content'] = cleaned_data['button_content']
        return cleaned_data
Exemplo n.º 30
0
class UpdateForm_(Bootstrap3Form):

    # login = forms.CharField(label='Логин', min_length=2, max_length=20, required=True,
    #                       error_messages={'invalid': 'Поле должно быть заполнено'})
    firstname = fields.CharField(label='Имя',
                                 min_length=2,
                                 max_length=100,
                                 required=True)
    lastname = fields.CharField(label='Фамилия',
                                min_length=2,
                                max_length=100,
                                required=True)
    middlename = fields.CharField(label='Отчество',
                                  min_length=2,
                                  max_length=100,
                                  required=True)
    address = fields.CharField(label='Адрес',
                               required=True,
                               widget=forms.Textarea(attrs={
                                   'cols': '80',
                                   'rows': '3'
                               }))
    tel = fields.RegexField(
        r'^\+?[0-9 .-]{4,14}$',
        label='Телефон',
        max_length=15,
        error_messages={'invalid': '4-14 цифр, начинается с \'+\''})
    old_password = fields.CharField(
        label='Текущий пароль',
        widget=forms.PasswordInput,
        required=False,
        min_length=5,
        error_messages={'invalid': 'Не менее 5 символов'})
    password_re = fields.CharField(
        label='Новый пароль',
        widget=forms.PasswordInput,
        required=False,
        min_length=5,
        error_messages={'invalid': 'Не менее 5 символов'})
    password_re2 = fields.CharField(
        label='Новый пароль еще раз',
        widget=forms.PasswordInput,
        required=False,
        min_length=5,
        error_messages={'invalid': 'Не менее 5 символов'})