Example #1
0
class UserSignupForm(SignupForm):

    email = forms.EmailField(
        max_length=80,
        required=True,
        label="E-mail",
        widget=forms.EmailInput(attrs={
            'placeholder': 'Your e-mail address',
            'class': 'form-control'
        }))
    email2 = forms.EmailField(
        max_length=80,
        required=True,
        label="Confirm E-mail",
        widget=forms.EmailInput(attrs={
            'placeholder': 'Confirm your e-mail address',
            'class': 'form-control'
        }))
    first_name = forms.CharField(
        max_length=50,
        required=False,
        label="First name",
        widget=forms.TextInput(attrs={
            'placeholder': 'Your first name',
            'class': 'form-control'
        }))
    last_name = forms.CharField(
        max_length=50,
        required=False,
        label="Last name",
        widget=forms.TextInput(attrs={
            'placeholder': 'Your last name',
            'class': 'form-control'
        }))
    terms_of_service = forms.BooleanField(required=False)
    newsletter = forms.BooleanField(required=False)
    privacy = forms.BooleanField()

    def __init__(self, *args, **kwargs):

        ignore_email2 = kwargs.pop('ignore_email2')
        data = super(UserSignupForm, self).__init__(*args, **kwargs)
        if ignore_email2:
            self.fields['email2'].required = False

        return data

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()
        if self.cleaned_data.get('newsletter'):
            user.subscribe_to_newsletter(request)
Example #2
0
class Plugin_ContactForm(IonywebContentForm, forms.Form):
    """
    Contact form use to display the plugin
    """

    name = forms.CharField(label=_(u'Name :'), required=False)
    mail = forms.EmailField(label=_(u'Email *:'))
    subject = forms.CharField(label=_(u'Object :'), required=False)
    message = forms.CharField(label=_(u"Message *:"), widget=forms.Textarea)

    def send(self, mails=[], default_subject=""):

        if self.is_valid():
            if not mails:
                mails = [a[1] for a in settings.ADMINS]

            if default_subject:
                default_subject = u'[' + default_subject + ']'

            subject = u'[%s]%s %s' % (settings.SITE_NAME, default_subject,
                                      self.cleaned_data['subject'])

            msg = EmailMessage(subject, self.cleaned_data['message'],
                               self.cleaned_data['mail'], mails)
            try:
                msg.send()
            except:
                return False

            return True

        return False
Example #3
0
class PasswordResetForm(auth.forms.PasswordResetForm):
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={
            'placeholder': _('*****@*****.**'),
            'class': 'form-control'
        }),
        label=_('Email address'))
Example #4
0
class UserEmailConfirmationForm(forms.Form):
    email = forms.EmailField()
    secret = forms.CharField(min_length=32, max_length=32)
    user_id = forms.IntegerField()

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(UserEmailConfirmationForm, self).__init__(*args, **kwargs)

    def clean_user_id(self):
        user_id = self.cleaned_data['user_id']
        if user_id != self.user.pk:
            raise forms.ValidationError(
                _('Logged in user does not match this link!')
            )
        return user_id

    def clean(self):
        check = AccountManager(self.user).check_confirmation_secret(
            self.cleaned_data['secret'],
            self.cleaned_data['email'],
        )
        if not check:
            raise forms.ValidationError(
                _('Link is invalid or has expired!')
            )
        return self.cleaned_data

    def save(self):
        self.user.email = self.cleaned_data['email']
        self.user.save()
Example #5
0
class SettingsForm(forms.ModelForm):
	start = forms.DateField(input_formats=('%d.%m.%Y',), error_messages=RU_ERRORS, widget=forms.DateInput(attrs={'class': 'input-small form-control'}))
	finish = forms.DateField(input_formats=('%d.%m.%Y',), error_messages=RU_ERRORS, widget=forms.DateInput(attrs={'class': 'input-small form-control'}))
	time = forms.TimeField(input_formats=('%H:%M',), error_messages=RU_ERRORS, widget=forms.TimeInput(attrs={'class': 'form-control', 'id': 'alert-time-display', 'value': '12:00'}))
	email = forms.EmailField(required=False, error_messages=RU_ERRORS, widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': u'Укажите email для оповещений'}))
	phone = forms.RegexField(r'^\+79\d{9}$', '^\+79\d{9}$', required=False, error_messages=RU_ERRORS, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': u'+79123456789'}))
	user_time = forms.CharField(widget=forms.HiddenInput())

	class Meta:
		model = Alert
		widgets = {
			'alert_email': forms.CheckboxInput(attrs={'id': 'email-alert'}),
			'alert_sms': forms.CheckboxInput(attrs={'id': 'sms-alert'}),
			'period': forms.Select(attrs={'class': 'form-control'}),
		}
		exclude = ['user', 'alert_server_time']

	def clean(self):
		cleaned_data = super(SettingsForm, self).clean()

		if cleaned_data.get('alert_email') and cleaned_data.get('email') == '':
			raise forms.ValidationError(u'Введите email')

		if cleaned_data.get('alert_sms') and cleaned_data.get('phone') == '':
			raise forms.ValidationError(u'Введите номер телефона')
	
		return cleaned_data
Example #6
0
 def __init__(self, foirequest, user, *args, **kwargs):
     self.foirequest = foirequest
     self.user = user
     super(FollowRequestForm, self).__init__(*args, **kwargs)
     if not self.user.is_authenticated():
         self.fields["email"] = forms.EmailField(label=_("Your Email address"),
                 widget=forms.TextInput(attrs={"placeholder": _("email address")}))
Example #7
0
class UserSignupForm(SignupForm):
    email = forms.EmailField(
        max_length=80,
        required=True,
        label="E-mail",
        widget=forms.EmailInput(attrs={
            'placeholder': 'Your e-mail address',
            'class': 'form-control'
        }))
    first_name = forms.CharField(
        max_length=50,
        required=False,
        label="First name",
        widget=forms.TextInput(attrs={
            'placeholder': 'Your first name',
            'class': 'form-control'
        }))
    last_name = forms.CharField(
        max_length=50,
        required=False,
        label="Last name",
        widget=forms.TextInput(attrs={
            'placeholder': 'Your last name',
            'class': 'form-control'
        }))
    terms_of_service = forms.BooleanField(required=True)
    newsletter = forms.BooleanField(required=False)

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()
        if self.cleaned_data.get('newsletter'):
            user.subscribe_to_newsletter(request)
Example #8
0
class RegistrationForm(forms.Form):
    name = forms.CharField(label='First- and Lastname', max_length=50)
    email = forms.EmailField(max_length=50,
                             help_text='Please enter a valid email.')
    age = AgeField()
    short_biography = forms.CharField(max_length=200)
    comment = forms.CharField(widget=widgets.Textarea)
Example #9
0
class EditCurrentUser(forms.Form):

    email = forms.EmailField(label=_(u"Email Address"),
                             help_text="",
                             required=True)

    def __init__(self, user, *args, **kwargs):
        super(EditCurrentUser, self).__init__(*args, **kwargs)
        self.fields['email'].initial = user.email

    def clean_email(self):
        "Check the email domain for MX DNS record"
        email = self.cleaned_data['email']

        user, domain = email.split('@')

        # Checking if the domain contains a MX record
        try:
            answers = dns.resolver.query(domain, 'MX')
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
            raise forms.ValidationError(
                _(u"Emails from this domain are not "
                  u"accepted"))
        else:
            return email

    def save(self, user, *args, **kwargs):
        user.email = self.cleaned_data['email']
        user.save()
Example #10
0
class TeamPlayerForm(forms.Form):
    first_name = forms.CharField(max_length=100, required=True)
    last_name = forms.CharField(max_length=100)
    number = forms.IntegerField()
    position = forms.CharField(max_length=3)
    #TODO: Autocreate this by first letter, last name, then number -> It should always be unique
    username = forms.CharField(max_length=30, required=True)
    email = forms.EmailField(max_length=100)
Example #11
0
class ContactPasswordResetForm(PasswordResetForm):
    email = forms.EmailField(
        label=_("Email"),
        max_length=254,
        error_messages={
            'unknown':
            _("We couldn't find a user for that email address. Please "
              "check that you typed the address correctly.")
        })

    def clean_email(self):
        """
        Validates that an active user exists with the given email address.
        """
        UserModel = get_user_model()
        email = self.cleaned_data["email"]
        self.users_cache = UserModel._default_manager.filter(
            business_email__iexact=email)
        if not len(self.users_cache):
            raise ValidationError(
                self.fields['email'].error_messages['unknown'])
        if not any(user.is_active for user in self.users_cache):
            # none of the filtered users are active
            raise ValidationError(
                self.fields['email'].error_messages['unknown'])
        return email

    def save(self,
             subject,
             email_template_name='registration/password_reset_email.html',
             use_https=False,
             token_generator=default_token_generator,
             from_email=None,
             request=None):
        """
        Generates a one-use only link for resetting password and sends to the
        user.
        """
        for user in self.users_cache:
            ctx = {
                'email': user.business_email,
                'site': settings.SITE_HOSTNAME,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': use_https and 'https' or 'http',
                'site_name': settings.SITE_NAME,
                'contact_address': settings.CONTACT_ADDRESS,
            }
            options = {
                'subject': subject,
                'from_email': from_email,
                'to': [user.business_email],
                'template_name': email_template_name,
                'context': ctx
            }
            mail.notify(options)
Example #12
0
class PublicBodyForm(forms.Form):
    name = forms.CharField(label=_("Name of Public Body"))
    description = forms.CharField(label=_("Short description"),
                                  widget=forms.Textarea,
                                  required=False)
    email = forms.EmailField(
        widget=forms.EmailInput,
        label=_("Email Address for Freedom of Information Requests"))
    url = forms.URLField(label=_("Homepage URL of Public Body"))
Example #13
0
class DonateForm(forms.Form):
    """Form for accepting a donation."""

    name = pyoforms.StripCharField(max_length=200)
    email = forms.EmailField(max_length=255)
    phone = pyoforms.StripCharField(max_length=20)
    country_code = forms.TypedChoiceField(
        choices=model.Profile._meta.get_field('country_code').choices,
        widget=forms.RadioSelect(),
        )
    school = pyoforms.ModelChoiceField(
        queryset=model.School.objects.filter(auto=False).order_by('name'),
        empty_label=u"I'm not affiliated with a school or program",
        required=False,
        widget=SchoolRadioSelect,
        initial=u'',
        )
    addschool = forms.BooleanField(
        initial=False, required=False, widget=forms.HiddenInput)

    amount = pyoforms.StripCharField(max_length=20)


    def __init__(self, *args, **kwargs):
        """Also instantiate a nested SchoolForm."""
        super(DonateForm, self).__init__(*args, **kwargs)
        self.addschool_form = SchoolForm(self.data or None, prefix='addschool')


    def clean(self):
        """
        Verify password fields match and school is provided.

        If addschool is True, build a new School based on data in nested
        SchoolForm.

        If not, and no school was selected, auto-construct one.

        """
        data = self.cleaned_data
        if data.get('addschool'):
            if self.addschool_form.is_valid():
                data['school'] = self.addschool_form.save(commit=False)
            else:
                raise forms.ValidationError(
                    "Could not add a school.")
        else:
            # reinstantiate unbound addschool_form to avoid spurious errors
            self.addschool_form = SchoolForm(prefix='addschool')
            if data.get('email') and not data.get('school'):
                data['school'] = model.School(
                    name=(u"%f-%s" % (time.time(), data['email']))[:200],
                    postcode="",
                    auto=True,
                    )
        return data
Example #14
0
class UserLoginForm(forms.Form):
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'placeholder': _('*****@*****.**'),
            'class': 'form-control'
        }),
        label=_('Email address'))
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label=_('Password'))
Example #15
0
class ContactForm(forms.Form):

    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea)

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.add_input(Submit('submit', 'Submit'))
        super(ContactForm, self).__init__(*args, **kwargs)
Example #16
0
class ContactForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea)
    captcha = ReCaptchaField()
Example #17
0
class UserChangeEmailForm(forms.Form):
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'placeholder': _('*****@*****.**')}),
        label=_('New email address'))

    def clean_email(self):
        email = self.cleaned_data['email'].lower()
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError(
                _('A user with that email address already exists!'))

        return email
Example #18
0
class AllFieldsForm(forms.Form):
    boolean = forms.BooleanField()
    char = forms.CharField(max_length=50)
    choices = forms.ChoiceField(choices=ALPHA_CHOICES)
    date = forms.DateField()
    datetime = forms.DateTimeField()
    decimal = forms.DecimalField(decimal_places=2, max_digits=4)
    email = forms.EmailField()
    file_field = forms.FileField()
    file_path = forms.FilePathField(path='uploads/')
    float_field = forms.FloatField()
    generic_ip_address = forms.GenericIPAddressField()
    image = forms.ImageField()
    integer = forms.IntegerField()
    ip_address = forms.IPAddressField()
    multiple_choices = forms.MultipleChoiceField(choices=ALPHA_CHOICES)
    null_boolean = forms.NullBooleanField()
    regex_field = forms.RegexField(regex='^\w+$', js_regex='^[a-zA-Z]+$')
    slug = forms.SlugField()
    split_datetime = forms.SplitDateTimeField()
    time = forms.TimeField()
    typed_choices = forms.TypedChoiceField(choices=NUMERIC_CHOICES, coerce=int)
    typed_multiple_choices = forms.TypedMultipleChoiceField(
        choices=NUMERIC_CHOICES, coerce=int)
    url = forms.URLField()

    # GIS fields.
    if gis_forms:
        osm_point = gis.PointField(
            widget=mixin(gis.PointWidget, gis.BaseOsmWidget))
        osm_multipoint = gis.MultiPointField(
            widget=mixin(gis.MultiPointWidget, gis.BaseOsmWidget))
        osm_linestring = gis.LineStringField(
            widget=mixin(gis.LineStringWidget, gis.BaseOsmWidget))
        osm_multilinestring = gis.MultiLineStringField(
            widget=mixin(gis.MultiLineStringWidget, gis.BaseOsmWidget))
        osm_polygon = gis.PolygonField(
            widget=mixin(gis.PolygonWidget, gis.BaseOsmWidget))
        osm_multipolygon = gis.MultiPolygonField(
            widget=mixin(gis.MultiPolygonWidget, gis.BaseOsmWidget))

        gmap_point = gis.PointField(
            widget=mixin(gis.PointWidget, BaseGMapWidget))
        gmap_multipoint = gis.MultiPointField(
            widget=mixin(gis.MultiPointWidget, BaseGMapWidget))
        gmap_linestring = gis.LineStringField(
            widget=mixin(gis.LineStringWidget, BaseGMapWidget))
        gmap_multilinestring = gis.MultiLineStringField(
            widget=mixin(gis.MultiLineStringWidget, BaseGMapWidget))
        gmap_polygon = gis.PolygonField(
            widget=mixin(gis.PolygonWidget, BaseGMapWidget))
        gmap_multipolygon = gis.MultiPolygonField(
            widget=mixin(gis.MultiPolygonWidget, BaseGMapWidget))
Example #19
0
class SignInForm(Form):
    user_email = forms.EmailField(max_length=255, label=_("Seu email"))
    user_password = forms.CharField(widget=forms.PasswordInput,
                                    max_length=255,
                                    label=_("Sua senha"))
    user_remember_me = forms.BooleanField(label=_("Fique conectado"),
                                          help_text=_("Lembre de mim"),
                                          required=False)

    def __init__(self, *args, **kwargs):
        show_remember_me = kwargs.pop('show_remember_me')

        super(SignInForm, self).__init__(*args, **kwargs)
        if not show_remember_me:
            del self.fields['user_remember_me']
Example #20
0
class ArtistInfoForm(forms.ModelForm):
    state = USStateField(widget=floppyforms.Select(choices=STATE_CHOICES_WITH_EMPTY), required=False)
    country = floppyforms.ChoiceField(choices=COUNTRIES_WITH_EMPTY)
    payout_method = forms.ChoiceField(
        choices=User.PAYOUT_CHOICES,
        widget=forms.RadioSelect()
    )
    paypal_email_again = floppyforms.EmailField(required=False)

    class Meta:
        fields = ('first_name', 'last_name', 'address_1', 'address_2', 'city', 'zip', 'state', 'country',
                  'payout_method', 'paypal_email', 'paypal_email_again', 'taxpayer_id')
        model = User

    def __init__(self, *args, **kwargs):
        super(ArtistInfoForm, self).__init__(*args, **kwargs)
        for field in self.Meta.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'
        self.fields['state'].widget.attrs['class'] = 'form-control selectpicker'
        self.fields['country'].widget.attrs['class'] = 'form-control selectpicker'
        # default to US if nothing is set, initial not working as the form is bound
        if not self.initial['country']:
            self.initial['country'] = 'US'

    def clean(self):
        cleaned_data = super(ArtistInfoForm, self).clean()
        if cleaned_data.get('payout_method') == User.PAYOUT_CHOICES.PayPal:
            msg = u"This field is required."
            if not cleaned_data.get('paypal_email'):
                self.add_error('paypal_email', msg)
            if not cleaned_data.get('paypal_email_again'):
                self.add_error('paypal_email_again', msg)
            if cleaned_data.get('paypal_email') != cleaned_data.get('paypal_email_again'):
                raise forms.ValidationError(u'The two email addresses must match.')

        if cleaned_data.get('country') == 'US':
            state = cleaned_data.get('state')
            if not state:
                self.add_error('state', 'You must select a valid US state or territory.')
            taxpayer_id = cleaned_data.get('taxpayer_id')
            if not taxpayer_id:
                self.add_error('taxpayer_id', 'You must enter a valid taxpayer ID as a US citizen.')
            self.fields['state'].clean(state)
            self.fields['taxpayer_id'].clean(state)
        else:
            cleaned_data['state'] = ''
            cleaned_data['taxpayer_id'] = ''
        return cleaned_data
Example #21
0
class ContactForm(forms.Form):

    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    subject = forms.CharField(required=forms.Textarea)

    # http://stackoverflow.com/questions/1694447/how-to-set-an-event-handler-in-a-django-form-input-field
    # https://chriskief.com/2012/12/16/override-django-form-is_valid/
    # http://stackoverflow.com/questions/30424394/django-forms-how-to-override-field-validation
    # overriding field validation

    # Creating drop-down list
    sales = "Sales"
    marketing = "Marketing"
    hr = "Recruitment"
    customer = "customers"
    it = "IT"
    other = "Other/Not Specified"

    dep_choices = {(sales, 'Sales'), (marketing, 'Marketing'),
                   (hr, 'Recruitment'), (it, 'IT'), (customer, 'Customers'),
                   (other, 'Other/Not Specified')}

    # choice field would be tracked
    # http://stackoverflow.com/questions/1694447/how-to-set-an-event-handler-in-a-django-form-input-field
    # http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed
    # triggering changes inside current contact form instance

    # from experiments I found that 'attrs' below executes pure javascript
    # so I just used javascript to update image
    department = forms.ChoiceField(
        choices=dep_choices,
        # widget=forms.Select(attrs={'onchange': "alert(this.value)"}))
        widget=forms.Select(attrs={'onchange': 'changepic(this.value)'}))

    # set initial state
    department.initial = {'other', 'Other/Not Specified'}

    # http://stackoverflow.com/questions/16076420/django-dropdownlist-onchange-submission

    message = forms.CharField(widget=forms.Textarea(
        attrs={'style': 'resize:allow;'}))

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.add_input(Submit('submit', 'Submit'))
        # self.initial['department'] = ... # possible variant here # http://herself.movielady.net/2012/12/15/initial-value-in-djangos-admin-for-a-choice-field/
        super(ContactForm, self).__init__(*args, **kwargs)
Example #22
0
class SignInForm(Form):
    user_email = forms.EmailField(max_length=255, label=_("Your email"))
    user_password = forms.CharField(widget=forms.PasswordInput,
                                    max_length=255,
                                    label=_("Your password"))
    user_remember_me = forms.BooleanField(
        label=_("Stay Signed In"),
        help_text=_("Sign me In automatically next time"),
        required=False)

    def __init__(self, *args, **kwargs):
        show_remember_me = kwargs.pop('show_remember_me')

        super(SignInForm, self).__init__(*args, **kwargs)
        if not show_remember_me:
            del self.fields['user_remember_me']
Example #23
0
class CompleteSignupForm(SetPasswordForm):
    email = forms.EmailField()

    def __init__(self, user=None, *args, **kwargs):
        super(CompleteSignupForm, self).__init__(user, *args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_method = 'post'
        self.helper.form_tag = False
        self.helper.layout = Layout(
            'email',
            'password1',
            'password2',
            StrictButton('Complete registration', css_class="btn-primary", type="submit"),
        )
        self.fields['email'].read_only = True
        self.fields['email'].initial = self.user.email
        self.fields['email'].help_text = "This is used to log in to SmallsLIVE. You can update it now if you want to."
Example #24
0
class UserChangeForm(forms.Form):
    email = forms.EmailField(
        required=False,
        widget=forms.EmailInput(attrs={
            'placeholder': _('*****@*****.**'),
            'class': 'form-control'
        }),
        label=_('Your email address'))

    #    address = forms.CharField(max_length=300,
    #            label=_('Your mailing address'),
    #            help_text=_('Your address will never be displayed publicly.'),
    #            widget=forms.Textarea(attrs={'placeholder': _('Street, Post Code, City'),
    #                'class': 'form-control'}))

    #    field_order = ['email', 'newsletter', 'address']
    field_order = ['email', 'newsletter']

    def __init__(self, user, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)
        self.user = user
        # self.fields['address'].initial = self.user.address
        self.fields['email'].initial = self.user.email
        if HAVE_NEWSLETTER():
            self.fields['newsletter'] = forms.BooleanField(
                required=False, label=_("Newsletter"))
            self.fields['newsletter'].initial = self.user.newsletter
        self.order_fields(self.field_order)

    def clean_email(self):
        email = self.cleaned_data['email'].lower()
        if (self.user.email != email
                and get_user_model().objects.filter(email=email).exists()):
            raise forms.ValidationError(
                _('Another user with that email address already exists!'))
        return email

    def save(self):
        if 'address' in self.cleaned_data:
            self.user.address = self.cleaned_data['address']
        if HAVE_NEWSLETTER():
            self.user.newsletter = self.cleaned_data['newsletter']

        self.user.save()
Example #25
0
class ChangeEmailForm(AddEmailForm):
    email = forms.EmailField(
        max_length=80,
        required=True,
        label="E-mail",
        widget=forms.EmailInput(attrs={
            'placeholder': 'Your e-mail address',
            'class': 'form-control'
        }))

    def __init__(self, *args, **kwargs):
        super(ChangeEmailForm, self).__init__(*args, **kwargs)
        self.fields['email'].initial = self.user.email

    def save(self, request):
        old_email = EmailAddress.objects.get(email=self.user.email)
        old_email.change(request,
                         new_email=self.cleaned_data['email'],
                         confirm=True)
Example #26
0
class UserSendActivationMailForm(Form):
    email = forms.EmailField(
        label=_("Your E-mail Address"),
        help_text=
        _("Enter email address send activation e-mail to. It must be valid e-mail you used to register on forums."
          ),
        max_length=255)
    captcha_qa = QACaptchaField()
    recaptcha = ReCaptchaField()
    error_source = 'email'

    def clean_email(self):
        data = self.cleaned_data['email']
        try:
            self.found_user = User.objects.get_by_email(data)
        except User.DoesNotExist:
            raise ValidationError(
                _("There is no user with such e-mail address."))
        return data
Example #27
0
class BaseInviteForm(forms.Form):
    email = forms.EmailField()
    kind = forms.ChoiceField()
    choices = ()

    def __init__(self, request, content, *args, **kwargs):
        super(BaseInviteForm, self).__init__(*args, **kwargs)
        self.request = request
        self.content = content
        self.fields['kind'].choices = self.choices
        self.fields['kind'].initial = self.choices[0][0]

    def save(self):
        invite_class = get_invite_class(self.cleaned_data['kind'])
        invite, created = invite_class.get_or_create(
            request=self.request,
            email=self.cleaned_data['email'],
            content=self.content,
        )
        if created:
            invite.send()
Example #28
0
class NewsletterSubscribeForm(forms.Form):
    email = forms.EmailField(max_length=80,
                             required=True,
                             label="E-mail",
                             widget=forms.EmailInput(
                                 attrs={
                                     'placeholder': 'Your e-mail address',
                                     'class': 'newsletters__subscribe__input'
                                 }))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(NewsletterSubscribeForm, self).__init__(*args, **kwargs)
        if self.user:
            self.fields['email'].initial = self.user.email

    def subscribe(self, request=None):
        if self.user:
            self.user.subscribe_to_newsletter(request)
        else:
            subscribe_to_newsletter(self.cleaned_data.get('email'), request)
Example #29
0
class RegistrationBasicForm(forms.Form):
    """
    First step of the Registration form, requiring User's basic info
    """
    user_name = forms.CharField(max_length=50)
    email = forms.EmailField(max_length=100)
    first_name = forms.CharField(max_length=30, required=False)
    last_name = forms.CharField(max_length=30, required=False)
    password = forms.CharField(max_length=30, widget=forms.PasswordInput())
    confirm_password = forms.CharField(max_length=30,
                                       widget=forms.PasswordInput())

    def clean_email(self):
        email = self.cleaned_data['email']
        if email:
            if User.objects.filter(Q(email=email)):
                raise forms.ValidationError(
                    u'This email address is already registered.')

        return email

    def clean_user_name(self):
        username = self.cleaned_data['user_name']
        if username:
            if User.objects.filter(Q(username=username)):
                raise forms.ValidationError(u'This username is already taken.')

        return username

    def clean(self):
        cleaned_data = self.cleaned_data
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        if password and password != confirm_password:
            msg = u'Passwords do not match. Please try again.'
            self._errors['confirm_password'] = self.error_class([msg])

        return cleaned_data
Example #30
0
class RegistrationForm(forms.Form):
    #this has to be under a different name due to the fact that register form popup may
    #appear after user login modal, and if that happens, 'div_id_fieldname' would only pick up the
    #username field from login pop so login.js applyFormFieldError wouldn't work for username
    username_register = forms.CharField(max_length=50, label=u'Username')
    email = forms.EmailField(max_length=100)
    password = forms.CharField(max_length=30, widget=forms.PasswordInput())
    confirm_password = forms.CharField(max_length=30,
                                       widget=forms.PasswordInput())

    def clean_email(self):
        email = self.cleaned_data['email']
        if email:
            if User.objects.filter(Q(email=email)):
                raise forms.ValidationError(
                    u'This email address is already registered.')

        return email

    def clean_username_register(self):
        username = self.cleaned_data['username_register']
        if username:
            if User.objects.filter(Q(username=username)):
                raise forms.ValidationError(u'This username is already taken.')

        return username

    def clean(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')

        if password and password != confirm_password:
            msg = u'Passwords do not match. Please try again.'
            self._errors['confirm_password'] = self.error_class([msg])

        return self.cleaned_data