Пример #1
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'))
Пример #2
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'))
Пример #3
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()
Пример #4
0
class ShopOrderAddendumFormMixin(OrderButtonForm):
    show_history = fields.BooleanField(
        label=_("Show History"),
        initial=True,
        required=False,
        help_text=_("Show historical annotations."),
    )

    class Meta:
        entangled_fields = {'glossary': ['show_history']}
Пример #5
0
class AcceptConditionForm(DialogForm):
    scope_prefix = 'accept_condition'

    accept = fields.BooleanField(
        required=True,
        widget=CheckboxInput(),
    )

    def __init__(self, data=None, initial=None, *args, **kwargs):
        plugin_id = data and data.get('plugin_id') or initial and initial.get('plugin_id') or 'none'
        scope_prefix = '{0}.plugin_{1}'.format(self.scope_prefix, plugin_id)
        self.form_name = '{0}.plugin_{1}'.format(self.form_name, plugin_id)
        super().__init__(data=data, initial=initial, scope_prefix=scope_prefix, *args, **kwargs)

    @classmethod
    def form_factory(cls, request, data, cart):
        data = data or {'accept': False}
        accept_form = cls(data=data)
        return accept_form
Пример #6
0
class ChoiceForm(NgFormValidationMixin, NgForm):
    choose = fields.BooleanField(required=True, label='Choose')
Пример #7
0
class AddressForm(DialogModelForm):
    # field to be superseeded by a select widget
    active_priority = fields.CharField(
        required=False,
        widget=widgets.HiddenInput(),
    )

    use_primary_address = fields.BooleanField(
        label=
        "use primary address",  # label will be overridden by Shipping/Billing/AddressForm
        required=False,
        initial=True,
        widget=widgets.CheckboxInput(),
    )

    # JS function to filter form_entities after removing an entity
    js_filter = "var list = [].slice.call(arguments); return list.filter(function(a) {{ return a.value != '{}'; }});"
    plugin_fields = ['plugin_id', 'plugin_order', 'use_primary_address']

    class Meta:
        exclude = (
            'customer',
            'priority',
        )

    def __init__(self, initial=None, instance=None, *args, **kwargs):
        self.multi_addr = kwargs.pop('multi_addr', False)
        self.allow_use_primary = kwargs.pop('allow_use_primary', False)
        self.form_entities = kwargs.pop('form_entities', [])
        if instance:
            cart = kwargs['cart']
            initial = dict(initial or {}, active_priority=instance.priority)
            if instance.address_type == 'shipping':
                initial['use_primary_address'] = cart.shipping_address is None
            else:  # address_type == billing
                initial['use_primary_address'] = cart.billing_address is None
        super(AddressForm, self).__init__(initial=initial,
                                          instance=instance,
                                          *args,
                                          **kwargs)

    @classmethod
    def get_model(cls):
        return cls.Meta.model

    @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] = [
                    'has-feedback', 'form-group',
                    'shop-address-{}'.format(name)
                ]
        return css_classes

    @classmethod
    def form_factory(cls, request, data, cart):
        """
        From the given request, update the database model.
        If the form data is invalid, return an error dictionary to update the response.
        """
        # search for the associated address DB instance or create a new one
        current_address = cls.get_address(cart)
        try:
            active_priority = int(data.get('active_priority'))
        except (ValueError, TypeError):
            if data.get('use_primary_address'):
                active_priority = 'nop'
            else:
                active_priority = data.get('active_priority', 'new')
            active_address = cls.get_model().objects.get_fallback(
                customer=request.customer)
        else:
            filter_args = dict(customer=request.customer,
                               priority=active_priority)
            active_address = cls.get_model().objects.filter(
                **filter_args).first()

        if data.pop('remove_entity', False):
            if active_address and (isinstance(active_priority, int)
                                   or data.get('is_pending')):
                active_address.delete()
            old_address = cls.get_model().objects.get_fallback(
                customer=request.customer)
            if old_address:
                faked_data = dict(data)
                faked_data.update(
                    dict((field.name,
                          old_address.serializable_value(field.name))
                         for field in old_address._meta.fields))
                address_form = cls(data=faked_data)
                remove_entity_filter = cls.js_filter.format(active_priority)
                address_form.data.update(
                    active_priority=str(old_address.priority),
                    remove_entity_filter=mark_safe(remove_entity_filter),
                )
            else:
                address_form = cls()
                address_form.data.update(
                    active_priority='add',
                    plugin_id=data.get('plugin_id'),
                    plugin_order=data.get('plugin_order'),
                )
            address_form.set_address(cart, old_address)
        elif active_priority == 'add':
            # Add a newly filled address for the given customer
            address_form = cls(data=data, cart=cart)
            if address_form.is_valid():
                # prevent adding the same address twice
                all_field_names = [
                    f.name for f in cls.get_model()._meta.get_fields()
                ]
                filter_args = dict((attr, val)
                                   for attr, val in address_form.data.items()
                                   if attr in all_field_names and val)
                filter_args.update(customer=request.customer)
                try:
                    existing_address = cls.get_model().objects.get(
                        **filter_args)
                except cls.get_model().DoesNotExist:
                    next_address = address_form.save(commit=False)
                    if next_address:
                        next_address.customer = request.customer
                        next_address.priority = cls.get_model(
                        ).objects.get_max_priority(request.customer) + 1
                        next_address.save()
                        address_form.data.update(
                            active_priority=str(next_address.priority))
                    else:
                        address_form.data.update(active_priority='nop')
                    address_form.set_address(cart, next_address)
                else:
                    address_form.set_address(cart, existing_address)
        elif active_priority == 'new' or active_address is None and not data.get(
                'use_primary_address'):
            # customer selected 'Add another address', hence create a new empty form
            initial = dict((key, val) for key, val in data.items()
                           if key in cls.plugin_fields)
            address_form = cls(initial=initial)
            address_form.data.update(address_form.get_initial_data())
            address_form.data.update(active_priority='add')
        elif current_address == active_address:
            # an existing entity of AddressModel was edited
            address_form = cls(data=data, instance=active_address, cart=cart)
            if address_form.is_valid():
                next_address = address_form.save()
                address_form.set_address(cart, next_address)
        else:
            # an address with another priority was selected
            initial = dict(data)
            for attr in cls().get_initial_data().keys():
                if hasattr(active_address, attr):
                    initial.update({attr: getattr(active_address, attr)})
            initial.update(active_priority=str(active_address.priority))
            address_form = cls(data=initial,
                               instance=current_address,
                               cart=cart)
            address_form.set_address(cart, active_address)
        return address_form

    def get_response_data(self):
        return self.data

    def full_clean(self):
        super(AddressForm, self).full_clean()
        if self.is_bound and self['use_primary_address'].value():
            # reset errors, since then the form is always regarded as valid
            self._errors = ErrorDict()

    def save(self, commit=True):
        if not self['use_primary_address'].value():
            return super(AddressForm, self).save(commit)

    def as_div(self):
        # Intentionally rendered without field `use_primary_address`, this must be added
        # on top of the form template manually
        self.fields.pop('use_primary_address', None)
        return super(AddressForm, self).as_div()

    def as_text(self):
        bound_field = self['use_primary_address']
        if bound_field.value():
            return bound_field.field.widget.choice_label
        return super(AddressForm, self).as_text()
class SubscribeForm(NgFormValidationMixin, Bootstrap3Form):
    use_required_attribute = False

    CONTINENT_CHOICES = [('am', 'America'), ('eu', 'Europe'), ('as', 'Asia'),
                         ('af', 'Africa'), ('au', 'Australia'),
                         ('oc', 'Oceania'), ('an', 'Antartica')]
    TRAVELLING_BY = [('foot', 'Foot'), ('bike', 'Bike'), ('mc', 'Motorcycle'),
                     ('car', 'Car'), ('public', 'Public Transportation'),
                     ('train', 'Train'), ('air', 'Airplane')]
    NOTIFY_BY = [('email', 'EMail'), ('phone', 'Phone'), ('sms', 'SMS'),
                 ('postal', 'Postcard')]

    first_name = fields.CharField(label='First name',
                                  min_length=3,
                                  max_length=20)

    last_name = fields.RegexField(
        r'^[A-Z][a-z -]?',
        label='Last name',
        error_messages={'invalid': 'Last names shall start in upper case'})

    sex = fields.ChoiceField(
        choices=(('m', 'Male'), ('f', 'Female')),
        widget=widgets.RadioSelect,
        error_messages={'invalid_choice': 'Please select your sex'})

    email = fields.EmailField(label='E-Mail',
                              required=True,
                              help_text='Please enter a valid email address')

    subscribe = fields.BooleanField(label='Subscribe Newsletter',
                                    initial=False,
                                    required=False)

    phone = fields.RegexField(
        r'^\+?[0-9 .-]{4,25}$',
        label='Phone number',
        error_messages={
            'invalid': 'Phone number have 4-25 digits and may start with +'
        })

    birth_date = fields.DateField(
        label='Date of birth',
        widget=widgets.DateInput(
            attrs={'validate-date': '^(\d{4})-(\d{1,2})-(\d{1,2})$'}),
        help_text='Allowed date format: yyyy-mm-dd')

    continent = fields.ChoiceField(
        label='Living on continent',
        choices=CONTINENT_CHOICES,
        error_messages={'invalid_choice': 'Please select your continent'})

    weight = fields.IntegerField(
        label='Weight in kg',
        min_value=42,
        max_value=95,
        error_messages={'min_value': 'You are too lightweight'})

    height = fields.FloatField(
        label='Height in meters',
        min_value=1.48,
        max_value=1.95,
        step=0.05,
        error_messages={'max_value': 'You are too tall'})

    traveling = fields.MultipleChoiceField(
        label='Traveling by',
        choices=TRAVELLING_BY,
        help_text='Choose one or more carriers',
        required=True)

    notifyme = fields.MultipleChoiceField(
        label='Notify by',
        choices=NOTIFY_BY,
        widget=widgets.CheckboxSelectMultiple,
        required=True,
        help_text='Must choose at least one type of notification')

    annotation = fields.CharField(label='Annotation',
                                  required=True,
                                  widget=widgets.Textarea(attrs={
                                      'cols': '80',
                                      'rows': '3'
                                  }))

    agree = fields.BooleanField(label='Agree with our terms and conditions',
                                initial=False,
                                required=True)

    password = fields.CharField(label='Password',
                                widget=widgets.PasswordInput,
                                validators=[validate_password],
                                help_text='The password is "secret"')

    confirmation_key = fields.CharField(max_length=40,
                                        required=True,
                                        widget=widgets.HiddenInput(),
                                        initial='hidden value')
Пример #9
0
class ChoiceForm(NgModelFormMixin, NgForm):
    scope_prefix = 'form_data'

    choose = fields.BooleanField(required=True, label='Choose')
Пример #10
0
class EditCartForm(Bootstrap3Form):
    status = fields.BooleanField(label='Корзина/Заказ',
                                 widget=forms.CheckboxInput,
                                 required=True)
Пример #11
0
class RegisterUserForm(NgModelFormMixin, NgFormValidationMixin, UniqueEmailValidationMixin, Bootstrap3ModelForm):
    form_name = 'register_user_form'
    scope_prefix = 'form_data'
    field_css_classes = 'input-group has-feedback'

    email = fields.EmailField(label=_("Your e-mail address"))

    preset_password = fields.BooleanField(
        label=_("Preset password"),
        widget=widgets.CheckboxInput(),
        required=False,
        help_text=_("Send a randomly generated password to your e-mail address."))

    password1 = fields.CharField(
        label=_("Choose a password"),
        widget=widgets.PasswordInput,
        min_length=6,
        help_text=_("Minimum length is 6 characters."),
    )

    password2 = fields.CharField(
        label=_("Repeat password"),
        widget=widgets.PasswordInput,
        min_length=6,
        help_text=_("Confirm password."),
    )

    class Meta:
        model = CustomerModel
        fields = ['email', 'password1', 'password2']

    def __init__(self, data=None, instance=None, *args, **kwargs):
        if data and data.get('preset_password', False):
            pwd_length = max(self.base_fields['password1'].min_length or 8, 8)
            password = get_user_model().objects.make_random_password(pwd_length)
            data['password1'] = data['password2'] = password
        super(RegisterUserForm, self).__init__(data=data, instance=instance, *args, **kwargs)

    def clean(self):
        cleaned_data = super(RegisterUserForm, self).clean()
        # check for matching passwords
        if 'password1' not in self.errors and 'password2' not in self.errors:
            if cleaned_data['password1'] != cleaned_data['password2']:
                msg = _("Passwords do not match")
                raise ValidationError(msg)
        return cleaned_data

    def save(self, request=None, commit=True):
        self.instance.user.is_active = True
        self.instance.user.email = self.cleaned_data['email']
        self.instance.user.set_password(self.cleaned_data['password1'])
        self.instance.recognize_as_registered(request, commit=False)
        customer = super(RegisterUserForm, self).save(commit)
        password = self.cleaned_data['password1']
        if self.cleaned_data['preset_password']:
            self._send_password(request, customer.user, password)
        user = authenticate(username=customer.user.username, password=password)
        login(request, user)
        return customer

    def _send_password(self, request, user, password):
        current_site = get_current_site(request)
        context = {
            'site_name': current_site.name,
            'absolute_base_uri': request.build_absolute_uri('/'),
            'email': user.email,
            'password': password,
            'user': user,
        }
        subject = select_template([
            '{}/email/register-user-subject.txt'.format(app_settings.APP_LABEL),
            'shop/email/register-user-subject.txt',
        ]).render(context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = select_template([
            '{}/email/register-user-body.txt'.format(app_settings.APP_LABEL),
            'shop/email/register-user-body.txt',
        ]).render(context)
        user.email_user(subject, body)
Пример #12
0
class RegisterUserForm(NgModelFormMixin, NgFormValidationMixin,
                       UniqueEmailValidationMixin, Bootstrap3ModelForm):
    form_name = 'register_user_form'
    scope_prefix = 'form_data'
    field_css_classes = 'input-group has-feedback'

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

    preset_password = fields.BooleanField(
        label=_("Preset password"),
        widget=widgets.CheckboxInput(),
        required=False,
        help_text=_(
            "Send a randomly generated password to your e-mail address."),
    )

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

    password1 = fields.CharField(
        label=_("New password"),
        widget=widgets.PasswordInput(attrs={'placeholder': _("Password")}),
        strip=False,
        help_text=password_validation.password_validators_help_text_html(),
    )

    password2 = fields.CharField(
        label=_("New password confirmation"),
        strip=False,
        widget=widgets.PasswordInput(attrs={'placeholder': _("Password")}),
        help_text=format_html('<ul><li>{}</li></ul>',
                              _("Confirm the password.")),
    )

    class Meta:
        model = CustomerModel
        fields = ['email', 'password1', 'password2']

    def __init__(self, data=None, instance=None, *args, **kwargs):
        if data and data.get('preset_password', False):
            pwd_length = max(self.base_fields['password1'].min_length or 8, 8)
            password = get_user_model().objects.make_random_password(
                pwd_length)
            data['password1'] = data['password2'] = password
        super(RegisterUserForm, self).__init__(data=data,
                                               instance=instance,
                                               *args,
                                               **kwargs)

    def clean(self):
        cleaned_data = super(RegisterUserForm, self).clean()
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')
        if password1 and password2:
            if password1 != password2:
                raise ValidationError(
                    self.error_messages['password_mismatch'],
                    code='password_mismatch',
                )
        password_validation.validate_password(password2)
        return cleaned_data

    def save(self, request=None, commit=True):
        self.instance.user.is_active = True
        self.instance.user.email = self.cleaned_data['email']
        self.instance.user.set_password(self.cleaned_data['password1'])
        self.instance.recognize_as_registered(request, commit=False)
        customer = super(RegisterUserForm, self).save(commit)
        password = self.cleaned_data['password1']
        if self.cleaned_data['preset_password']:
            self._send_password(request, customer.user, password)
        user = authenticate(username=customer.user.username, password=password)
        login(request, user)
        return customer

    def _send_password(self, request, user, password):
        current_site = get_current_site(request)
        context = {
            'site_name': current_site.name,
            'absolute_base_uri': request.build_absolute_uri('/'),
            'email': user.email,
            'password': password,
            'user': user,
        }
        subject = select_template([
            '{}/email/register-user-subject.txt'.format(
                app_settings.APP_LABEL),
            'shop/email/register-user-subject.txt',
        ]).render(context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = select_template([
            '{}/email/register-user-body.txt'.format(app_settings.APP_LABEL),
            'shop/email/register-user-body.txt',
        ]).render(context)
        user.email_user(subject, body)
Пример #13
0
class AddressForm(DialogModelForm):
    # field to be superseeded by a select widget
    active_priority = fields.CharField(
        required=False,
        widget=widgets.HiddenInput(),
    )

    use_primary_address = fields.BooleanField(
        label=
        "use primary address",  # label will be overridden by Shipping/Billing/AddressForm
        required=False,
        initial=True,
        widget=CheckboxInput(),
    )

    plugin_fields = ['plugin_id', 'plugin_order', 'use_primary_address']

    class Meta:
        exclude = ['customer', 'priority']

    def __init__(self,
                 initial=None,
                 instance=None,
                 cart=None,
                 *args,
                 **kwargs):
        self.cart = cart
        self.multi_addr = kwargs.pop('multi_addr', False)
        self.allow_use_primary = kwargs.pop('allow_use_primary', False)
        self.populate_siblings_summary()
        if instance:
            initial = dict(initial or {}, active_priority=instance.priority)
            if instance.address_type == 'shipping':
                initial['use_primary_address'] = cart.shipping_address is None
            else:  # address_type == billing
                initial['use_primary_address'] = cart.billing_address is None
        super(AddressForm, self).__init__(initial=initial,
                                          instance=instance,
                                          *args,
                                          **kwargs)

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

    @classmethod
    def get_model(cls):
        return cls.Meta.model

    @classmethod
    def form_factory(cls, request, data, cart):
        """
        From the given request, update the database model.
        If the form data is invalid, return an error dictionary to update the response.
        """
        # search for the associated address DB instance or create a new one
        current_address = cls.get_address(cart)
        try:
            active_priority = int(data.get('active_priority'))
        except (ValueError, TypeError):
            if data.get('use_primary_address'):
                active_priority = 'nop'
            else:
                active_priority = data.get('active_priority', 'add')
            active_address = cls.get_model().objects.get_fallback(
                customer=request.customer)
        else:
            filter_args = dict(customer=request.customer,
                               priority=active_priority)
            active_address = cls.get_model().objects.filter(
                **filter_args).first()

        if active_priority == 'add':
            # Add a newly filled address for the given customer
            address_form = cls(data=data, cart=cart)
            if address_form.is_valid():
                # prevent adding the same address twice
                all_field_names = [
                    f.name for f in cls.get_model()._meta.get_fields()
                ]
                filter_args = dict((attr, val)
                                   for attr, val in address_form.data.items()
                                   if attr in all_field_names and val)
                filter_args.update(customer=request.customer)
                try:
                    existing_address = cls.get_model().objects.get(
                        **filter_args)
                except cls.get_model().DoesNotExist:
                    next_address = address_form.save(commit=False)
                    if next_address:
                        next_address.customer = request.customer
                        next_address.priority = cls.get_model(
                        ).objects.get_max_priority(request.customer) + 1
                        next_address.save()
                        address_form.data.update(
                            active_priority=str(next_address.priority))
                    else:
                        address_form.data.update(active_priority='nop')
                    address_form.set_address(cart, next_address)
                else:
                    address_form.set_address(cart, existing_address)
                address_form.populate_siblings_summary()
        elif active_address is None and not data.get('use_primary_address'):
            # customer selected 'Add another address', hence create a new empty form
            initial = dict((key, val) for key, val in data.items()
                           if key in cls.plugin_fields)
            address_form = cls(initial=initial)
            address_form.data.update(address_form.get_initial_data())
            address_form.data.update(active_priority='add')
        elif current_address == active_address:
            # an existing entity of AddressModel was edited
            address_form = cls(data=data, instance=active_address, cart=cart)
            if address_form.is_valid():
                next_address = address_form.save()
                address_form.set_address(cart, next_address)
        else:
            # an address with another priority was selected
            initial = dict(data)
            for attr in cls().get_initial_data().keys():
                if hasattr(active_address, attr):
                    initial.update({attr: getattr(active_address, attr)})
            initial.update(active_priority=str(active_address.priority))
            address_form = cls(data=initial,
                               instance=current_address,
                               cart=cart)
            address_form.set_address(cart, active_address)
        return address_form

    def populate_siblings_summary(self):
        """
        Build a list of value-labels to populate the address choosing element
        """
        self.siblings_summary = []
        if self.cart is not None:
            AddressModel = self.get_model()
            addresses = AddressModel.objects.filter(
                customer=self.cart.customer).order_by('priority')
            for number, addr in enumerate(addresses, 1):
                self.siblings_summary.append({
                    'value':
                    str(addr.priority),
                    'label':
                    "{}. {}".format(
                        number,
                        addr.as_text().strip().replace('\n', ' – '))
                })

    def full_clean(self):
        super(AddressForm, self).full_clean()
        if self.is_bound and self['use_primary_address'].value():
            # reset errors, since then the form is always regarded as valid
            self._errors = ErrorDict()

    def save(self, commit=True):
        if not self['use_primary_address'].value():
            return super(AddressForm, self).save(commit)

    def get_response_data(self):
        return dict(self.data, siblings_summary=self.siblings_summary)

    def as_div(self):
        # Intentionally rendered without field `use_primary_address`, this must be added
        # on top of the form template manually
        self.fields.pop('use_primary_address', None)
        return super(AddressForm, self).as_div()

    def as_text(self):
        bound_field = self['use_primary_address']
        if bound_field.value():
            return bound_field.field.widget.choice_label
        return super(AddressForm, self).as_text()
Пример #14
0
class AdvancedSearchForm_(Bootstrap3Form):

    EDUMETODCODE_CHOICES = [
        ('', 'Любой'),
        ('01', 'Создание юридического лица до 01.07.2002'),
        ('02', 'Создание юридического лица путем реорганизации до 01.07.2002'),
        ('03',
         'Регистрации на территории Республики Крым или территории города федерального значения Севастополя на день принятия в Российскую Федерацию '
         ),
        ('11', 'Создание юридического лица'),
        ('21',
         'Создание юридического лица путем реорганизации в форме преобразования'
         ),
        ('22',
         'Создание юридического лица путем реорганизации в форме слияния'),
        ('23',
         'Создание юридического лица путем реорганизации в форме разделения'),
        ('24',
         'Создание юридического лица путем реорганизации в форме выделения'),
        ('26',
         'Создание юридического лица путем реорганизации в форме выделения с одновременным прекращением его деятельности в связи с присоединением к другому юридическому лицу'
         ),
        ('29',
         'СОЗДАНИЕ ЮРИДИЧЕСКОГО ЛИЦА ПУТЕМ РЕОРГАНИЗАЦИИ В ФОРМЕ СЛИЯНИЯ ЮРИДИЧЕСКИХ ЛИЦ, ВКЛЮЧАЯ ЮРИДИЧЕСКОЕ ЛИЦО, ДЕЯТЕЛЬНОСТЬ КОТОРОГО ПРЕКРАЩАЕТСЯ ОДНОВРЕМЕННО С ЕГО СОЗДАНИЕМ ПРИ РЕОРГАНИЗАЦИИ ДРУГОГО ЮРИДИЧЕСКОГО ЛИЦА В ФОРМЕ РАЗДЕЛЕНИЯ'
         ),
        ('30', 'Создание юридического лица путем реорганизации'),
    ]

    isaddr = fields.BooleanField(
        help_text='Сведения об адресе (месте нахождения)', required=False)
    isAddrFalsity = fields.BooleanField(
        help_text='Признак недостоверности адреса', required=False)
    isAddrChange = fields.BooleanField(
        help_text=
        'Сведения о принятии юридическим лицом решения об изменении места нахождения',
        required=False)
    index = fields.CharField(
        required=False,
        widget=widgets.TextInput(attrs={'placeholder': 'Индекс'}))
    codeKLADR = fields.CharField(
        required=False,
        widget=widgets.TextInput(attrs={'placeholder': 'Код адреса по КЛАДР'}))
    area = fields.CharField(
        required=False,
        widget=widgets.TextInput(attrs={'placeholder': 'Район (улус и т.п.)'}))
    city = fields.CharField(
        required=False,
        widget=widgets.TextInput(
            attrs={'placeholder': 'Город (волость и т.п.)'}))
    locality = fields.CharField(
        required=False,
        widget=widgets.TextInput(
            attrs={'placeholder': 'Населенный пункт (село и т.п.)'}))
    street = fields.CharField(
        required=False,
        widget=widgets.TextInput(
            attrs={'placeholder': 'Улица (проспект, переулок и т.п.)'}))

    isemail = fields.BooleanField(
        help_text='Сведения об адресе электронной почты юридического лица',
        required=False)
    email = fields.CharField(
        required=False,
        widget=widgets.TextInput(attrs={'placeholder': 'E-mail'}))

    isRegInfo = fields.BooleanField(
        help_text='Сведения о регистрации (образовании) юридического лица ',
        required=False)
    regNum = fields.CharField(
        required=False,
        widget=widgets.TextInput(
            attrs={'placeholder': 'Номер, присвоенный ЮЛ до 1 июля 2002 года'
                   }))
    codeEduMethod = fields.ChoiceField(
        initial='',
        label='Способ образования юридического лица',
        choices=EDUMETODCODE_CHOICES,
        widget=widgets.Select(attrs={'class': 'form-control-sm'}))