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'))
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'))
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
class GuestForm(UniqueEmailValidationMixin, DialogModelForm): scope_prefix = 'data.guest' form_name = 'customer_form' # Override form name to reuse template `customer-form.html` legend = _("Customer's Email") email = fields.EmailField(label=_("Email address")) class Meta: model = get_user_model( ) # since we only use the email field, use the User model directly fields = ['email'] 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
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()
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
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())
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)
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)
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' }))
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()
class EmailForm(NgFormValidationMixin, NgForm): email = fields.EmailField(label='E-Mail')
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')
class EmailForm(NgModelFormMixin, NgForm): scope_prefix = 'form_data' email = fields.EmailField(label='E-Mail')
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)
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)