Example #1
0
class PasswordResetForm(auth.forms.PasswordResetForm):
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'placeholder': _('*****@*****.**'),
            'class': 'form-control'
        }),
        label=_('Email address'))
Example #2
0
class TransferForm(forms.Form):
    email = forms.EmailField()
    bought_item = forms.ModelChoiceField(BoughtItem)

    def __init__(self, order, *args, **kwargs):
        super(TransferForm, self).__init__(*args, **kwargs)
        self.order = order
        self.fields['bought_item'].queryset = order.bought_items.filter(
            status=BoughtItem.BOUGHT, )

    def clean_email(self):
        email = self.cleaned_data['email']
        order_email = self.order.person.email if self.order.person else self.order.email
        if email == order_email:
            raise ValidationError("You can't transfer an item to yourself!")
        return email

    def clean_bought_item(self):
        bought_item = self.cleaned_data['bought_item']
        if not bought_item.can_transfer():
            raise forms.ValidationError(
                "This item is not eligible for transfer.")
        if TransferInvite.get_invites(bought_item).exists():
            raise ValidationError(
                "A transfer has already been initiated for this item.")
        return bought_item
Example #3
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 #4
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 #5
0
class MessageTopicForm(forms.ModelForm):

    subject = forms.CharField(
        max_length=100,
        label=_('A subject'),
        widget=TextInput(attrs={'placeholder': 'Contact'}))
    name = forms.CharField(
        max_length=30,
        label=_('Your full name'),
        widget=TextInput(attrs={'placeholder': 'Name Surname'}))
    email = forms.EmailField(
        label=_('Email'),
        widget=EmailInput(attrs={'placeholder': '*****@*****.**'}))

    class Meta:
        model = Message
        fields = [
            'message',
        ]
        widgets = {
            'message':
            Textarea(attrs={
                'placeholder': 'your contact reason...',
                'rows': 4,
            }),
        }

    def __init__(self, *args, **kws):
        super(MessageTopicForm, self).__init__(*args, **kws)
        self.fields.keyOrder = ['subject', 'name', 'email', 'message']
Example #6
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 #7
0
class ContatarAnuncianteForm(forms.Form):
    imovel_ref = forms.CharField(widget=forms.HiddenInput())
    email = forms.EmailField(
      widget=forms.TextInput(attrs={'placeholder': 'Digite seu email'}),
      label='E-mail')
    telefone = forms.CharField(
      widget=forms.TextInput(attrs={'placeholder': 'Digite seu telefone'}))
    nome = forms.CharField(
      widget=forms.TextInput(attrs={'placeholder': 'Digite seu nome'}),
      label='Nome')
    sobrenome = forms.CharField(
      widget=forms.TextInput(attrs={'placeholder': 'Digite seu sobrenome'}),
      label='Sobrenome')
    mensagem = forms.CharField(
      widget=forms.Textarea(attrs={'rows': 3,
                                   'cols': 45,
                                   'placeholder': 'Precisa mais informações do imóvel ou gostaria de agendar uma visita?'}, 
                                   ),
                            label='Mensagem',
                            required=False)

    def __init__(self, *args, **kwargs):
        super(ContatarAnuncianteForm, self).__init__(*args, **kwargs)
        

    def clean_telefone(self):
        telefone = self.cleaned_data['telefone']
        # not re.match(r'^(\(\d{2}\)) ?(\d{5}-\d{4}|\d{9}|\d{4}-\d{4}|\d{8})$',
        # telefone)
        if len(telefone) < 9:
            raise forms.ValidationError("Digite um telefone válido.")
        return telefone

    def envia_email(self):
        sender = MagicEmail("{0}".format(settings.DEFAULT_FROM_EMAIL))
        current_site = Site.objects.get_current()
        subject = "[SJC Vale Imóveis] Novo Contato: Ref: {0} ".format(
          self.cleaned_data['imovel_ref'])
        data = {'domain': current_site.domain,
                'body': subject,
                'imovel_ref': self.cleaned_data['imovel_ref'],
                'email': self.cleaned_data['email'],
                'telefone': self.cleaned_data['telefone'],
                'nome': self.cleaned_data['nome'],
                'sobrenome': self.cleaned_data['sobrenome'],
                'mensagem': self.cleaned_data['mensagem'],
                'url': reverse('buscador.lista.imovel_referencia',
                               args=[self.cleaned_data['imovel_ref'], ]), }

        email_contato = preferences.ImobiliariaPreferences.email_contato
        sender.using_template(
            "contato_cliente_imovel", data) \
            .with_subject(subject) \
            .reply_to(self.cleaned_data['email']) \
            .send_to([email_contato, ])
Example #8
0
class LecturerSignUpForm(UserCreationForm):
    # Declare user option fields to form
    first_name = forms.CharField(required=True, widget=forms.TextInput(
        attrs={'placeholder': 'First name'}))
    other_name = forms.CharField(required=True, widget=forms.TextInput(
        attrs={'placeholder': 'Other name'}))
    last_name = forms.CharField(required=True, widget=forms.TextInput(
        attrs={'placeholder': 'Surname '}))
    birth_place = forms.ChoiceField(required=True, choices=STATES)
    sex = forms.ChoiceField(required=True, choices=GENDER)
    birth_date = forms.DateField(required=True, widget=forms.DateInput)
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'placeholder': 'Enter email address'}), required=True)
    phone = forms.CharField(required=True, widget=forms.PhoneNumberInput(
        attrs={'placeholder': 'Mobile Number'}))
    address = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'House/Street/City/Town '}),
                              max_length=100)
    faculty = forms.ModelChoiceField(
        queryset=Faculty.objects.all(), required=False)

    class Meta:
        model = User
        fields = ('first_name', 'other_name', 'last_name', 'sex', 'birth_place', 'address',
                  'phone', 'email', 'faculty', 'birth_date', 'username',)

    # Add placeholder to UserCreationForm fields
    def __init__(self, *args, **kwargs):
        super(LecturerSignUpForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.update(
            {'placeholder': 'Choose A Unique Username'})
        self.fields['password1'].widget.attrs.update(
            {'placeholder': 'Choose A Password'})
        self.fields['password2'].widget.attrs.update(
            {'placeholder': 'Verify Password'})

    # Check if inputted email has not been used by another user
    def clean_email(self):
        email = self.cleaned_data['email']
        check = User.objects.values('email')
        if email in check:
            msg = 'this email has been used!'
            self.add_error('email', msg)
        return email

    def save(self, commit=True):
        user = super().save(commit=False)
        user.is_lecturer = True
        if commit:
            user.save()
            # Create lecturer object with user id
            Lecturer.objects.create(user=user)

        return user
class ConfirmacaoHomeForm(forms.Form):
    fone = forms.CharField(
        widget=TextInput(attrs={'placeholder': 'Ex: 12 9991 088 998'}),
        label=_("Telefone"), required=True,
        help_text='Se deseja alterar sua confirmação, entre com o mesmo telefone.')
    email = forms.EmailField(
        widget=EmailInput(attrs={'placeholder': 'Ex: [email protected]'}),
        label=_("E-mail (opcional)"), required=False)

    def __init__(self, *args, **kwargs):
        super(ConfirmacaoHomeForm, self).__init__(*args, **kwargs)
        self.fields['fone'].required = True

    def clean_fone(self):
        fone_validated = phone_validator(self.cleaned_data.get('fone'))
        self.cleaned_data['fone'] = fone_validated
        return self.cleaned_data['fone']
Example #10
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']

    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):
        self.user.address = self.cleaned_data['address']
        if HAVE_NEWSLETTER():
            self.user.newsletter = self.cleaned_data['newsletter']

        self.user.save()
Example #11
0
class SimpleRegistrationForm(forms.Form):
    """
    Simple registration form, request only user name, email and password.
    """
    first_name = forms.CharField(max_length=30, label=_("First name"))
    last_name = forms.CharField(max_length=30, label=_("Last name"))
    email = forms.EmailField(label=_("Email"))
    password1 = forms.CharField(max_length=128,
                                widget=forms.PasswordInput(),
                                label=_("Password"))
    password2 = forms.CharField(max_length=128,
                                widget=forms.PasswordInput(),
                                label=_("Password(retype)"))

    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(
                    _("The password fields did not match"))
        return self.cleaned_data

    def clean_first_name(self):
        if len(self.cleaned_data['first_name'].strip()) == 0:
            raise forms.ValidationError(_('You must provide a first name!'))
        return self.cleaned_data['first_name']

    def clean_last_name(self):
        if len(self.cleaned_data['last_name'].strip()) == 0:
            raise forms.ValidationError(_('You must provide a last name!'))
        return self.cleaned_data['last_name']

    def clean_email(self):
        # TODO Use mailgun flanker
        existing = User.objects.filter(
            email__iexact=self.cleaned_data['email'])
        if existing.exists():
            raise forms.ValidationError(_("This email already registered"))
        try:
            validate_email_domain(self.cleaned_data['email'])
        except dns.exception.DNSException, e:
            raise forms.ValidationError(_("Email seems to be wrong"))
        return self.cleaned_data['email']
Example #12
0
class EmailSubscribeForm(BetterBsModelForm):
    """Register to an emailing with just email address"""
    email = forms.EmailField(required=True,
                             label="",
                             widget=forms.TextInput(attrs={
                                 'placeholder': _('Email'),
                                 'size': '80'
                             }))

    class Meta:
        model = Contact
        fields = ('email', 'favorite_language')

    def __init__(self, *args, **kwargs):
        self.subscription_type = kwargs.pop('subscription_type', None)
        super(EmailSubscribeForm, self).__init__(*args, **kwargs)

        self.fields['favorite_language'].widget = forms.HiddenInput()
        if crm_settings.has_language_choices():
            self.fields['favorite_language'].initial = get_language()

    def save(self, request=None):
        """save"""
        contact = super(EmailSubscribeForm, self).save(commit=False)

        if crm_settings.ALLOW_SINGLE_CONTACT:
            contact.entity = Entity.objects.create(name=contact.email,
                                                   type=None,
                                                   is_single_contact=True)
        else:
            et_id = getattr(settings, 'BALAFON_INDIVIDUAL_ENTITY_ID', 1)
            entity_type = EntityType.objects.get(id=et_id)
            contact.entity = Entity.objects.create(name=contact.email,
                                                   type=entity_type)
        contact.save()
        # delete unknown contacts for the current entity
        contact.entity.contact_set.exclude(id=contact.id).delete()

        queryset = SubscriptionType.objects.filter(
            site=Site.objects.get_current())

        form_subscription_type = self.subscription_type
        default_subscription_type = emailing_settings.get_default_subscription_type(
        )
        if not form_subscription_type and default_subscription_type:
            form_subscription_type = default_subscription_type

        if form_subscription_type:
            queryset = queryset.filter(id=form_subscription_type)

        subscriptions = []
        for subscription_type in queryset:
            subscription = Subscription.objects.get_or_create(
                contact=contact, subscription_type=subscription_type)[0]
            subscription.accept_subscription = True
            subscription.subscription_date = datetime.now()
            subscription.save()
            subscriptions.append(subscription_type.name)

        create_subscription_action(contact, subscriptions)
        if subscriptions:
            send_notification_email(request, contact, [], "")
        else:
            send_notification_email(
                request, contact, [],
                "Error: " + ugettext("No subscription_type defined"))

        return contact
Example #13
0
class UserNewForm(forms.ModelForm):
    """ Formulaire d'inscription """

    # Constantes
    PASSWORD_LENGTH_MIN = 4
    USERNAME_LENGTH_MIN = 3
    USERNAME_LENGTH_MAX = 20
    FIRST_NAME_LENGTH_MAX = 20
    LAST_NAME_LENGTH_MAX = 40

    # Champs
    username = forms_.SlugField(max_length=30, min_length=4, label=_("User name"),
                                widget=forms_.TextInput(attrs={'placeholder': _("Letters, digits and underscores")}))
    email = forms_.EmailField(label=_("Email"), widget=forms_.TextInput(attrs={'placeholder': _("A non disposable email")}))
    email_confirm = forms_.EmailField(label=_("Retype email"))
    password_confirm = forms_.CharField(max_length=128, widget=forms_.PasswordInput(render_value=True), label=_("Retype password"))

    # Validation
    def clean_password(self):
        """" Valider et renvoyer les données du champ mot de passe """
        password = self.cleaned_data['password']
        if not password or len(password) < UserNewForm.PASSWORD_LENGTH_MIN:
            raise forms.ValidationError(_("Your password should be at least {min} characters long").format(min=UserNewForm.PASSWORD_LENGTH_MIN))
        return password

    def clean_password_confirm(self):
        """ Valider et renvoyer les données du champ confirmation de mot de passe """
        confirm = self.cleaned_data['password_confirm']
        if 'password_confirm' not in self.cleaned_data or confirm != self.cleaned_data.get('password'):
            raise forms.ValidationError(_("The password must be identical in both fields."))
        return confirm

    def clean_email(self):
        """ Valider et renvoyer les données du champ email """
        email = self.cleaned_data['email'].lower()
        credentials_form_check_email.send(sender=self, email=email)
        if get_user_model().objects.filter(email__iexact=email).exists():
            raise forms.ValidationError(_("This e-mail address is already in use."))
        return email

    def clean_email_confirm(self):
        """ Valider et renvoyer les données du champ confirmation de l'email """
        confirm = self.cleaned_data['email_confirm'].lower()
        if not self.fields['email_confirm'].required:
            return confirm
        if 'email_confirm' not in self.cleaned_data or confirm != self.cleaned_data.get('email'):
            raise forms.ValidationError(_("The email addresses must be identical."))
        return confirm

    def clean_name(self):
        """ Valider et renvoyer les données du champ nom """
        name = self.cleaned_data['name']
        credentials_form_check_name.send(sender=self, name=name)
        if len(name) > UserNewForm.FIRST_NAME_LENGTH_MAX:
            raise forms.ValidationError(_("Your first name must not exceed {max} characters").format(max=UserNewForm.FIRST_NAME_LENGTH_MAX))
        return name

    def clean_username(self):
        """ Valider et renvoyer les données du champ nom d'utilisateur """
        name = self.cleaned_data['username']
        credentials_form_check_username.send(sender=self, username=name)
        length = len(name)
        # Renvoyer une erreur si le pseudo est utilisé
        if get_user_model().objects.filter(username__iexact=name):
            raise forms.ValidationError(_("This nickname is already in use."))
        # Renvoyer une erreur si le pseudo est trop court ou long
        if length > UserNewForm.USERNAME_LENGTH_MAX or length < UserNewForm.USERNAME_LENGTH_MIN:
            raise forms.ValidationError(
                _("Your nickname should be between {min} and {max} characters long.").format(min=UserNewForm.USERNAME_LENGTH_MIN,
                                                                                             max=UserNewForm.USERNAME_LENGTH_MAX))
        return name.lower()

    def clean_eula(self):
        """ Valider et renvoyer les données du champ Accepter les CGU """
        checked = self.cleaned_data.get('eula', True)
        if 'eula' in self.cleaned_data and checked is False:
            raise forms.ValidationError(_("You must accept our EULA to proceed."))
        return True

    def __init__(self, *args, **kwargs):
        """ Initialiser le formulaire """
        super(UserNewForm, self).__init__(*args, **kwargs)

    # Métadonnées
    class Meta:
        model = get_user_model()
        fields = ('username', 'email', 'email_confirm', 'password', 'password_confirm')
        widgets = {'password': forms_.PasswordInput(render_value=True, attrs={'autocomplete': 'off'}),
                   'password_confirm': forms_.PasswordInput(render_value=False, attrs={'autocomplete': 'off'}),
                   'username': forms_.TextInput(attrs={'placeholder': _("4 characters minimum")}),
                   }
Example #14
0
class UserMessageForm(forms.ModelForm):
    class Meta():
        model = Message
        fields = (
            'title',
            'message',
            'messageType',
            'category',
            'address',
            'location',
            'is_anonymous',
            'allow_feedback',
            'is_virtual',
        )
        widgets = {
            'messageType': forms.HiddenInput(),
            'category': forms.CheckboxSelectMultiple(),
            'location': LeafletWidget(),
        }

    first_name = forms.CharField(label=_('First name'), required=False)
    last_name = forms.CharField(label=_('Last name'), required=False)
    email = forms.EmailField(label=_('Contact email'), required=False)
    phone = forms.CharField(label=_('Contact phone'), required=False)

    # address = forms.CharField(label=_('Address'))
    # TODO MultiPointField
    # coordinates = geoforms.PointField(
    # label=_('Coordinates'),
    # widget=LeafletWidget(),)

    def save(self, force_insert=False, force_update=False, commit=True):
        msg = super(UserMessageForm, self).save(commit=False)
        msg.additional_info = {
            'first_name': self.cleaned_data['first_name'],
            'last_name': self.cleaned_data['last_name'],
            'email': self.cleaned_data['email'],
            'phone': self.cleaned_data['phone'],
        }
        if commit:
            msg.save()
        return msg

    def clean(self):
        """
        Form validation.

        It is required that at least one from email and phone fields has been
        filled. If both fields are empty, throw ValidationError.
        """

        super(UserMessageForm, self).clean()
        ce = self.cleaned_data
        if ce['email'] == '' and ce['phone'] == '':
            self.errors['email'] = ErrorList([
                _("You must provide at least one from contact email or phone!"
                  ),
            ])
            self.errors['phone'] = ErrorList([
                _("You must provide at least one from contact email or phone!"
                  ),
            ])
            raise ValidationError(
                _("You must provide at least one from contact email or phone!")
            )
        return ce
Example #15
0
class ContactForm(forms.Form):
    """
    Contact Form
    """

    name = forms.CharField(required=True,
                           max_length=100,
                           label='Ihr Name',
                           widget=forms.TextInput(attrs={
                               'placeholder': 'Name',
                               'autofocus': 'autofocus'
                           }))
    email = forms.EmailField(
        required=True,
        max_length=100,
        label='Ihre Email',
        widget=forms.TextInput(attrs={'placeholder': 'Email'}))
    message = forms.CharField(
        required=True,
        label='Ihre Nachricht',
        widget=forms.Textarea(attrs={'placeholder': 'Nachricht'}))

    OUTGOING = u'Kontakt: Bestätigungsmail an den Kunden'
    INTERNAL = u'Weiterleitung Kontaktanfrage, bitte beantworten!'
    CONTACT_EMAIL = settings.MENTOKI_INFO_EMAIL

    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)

    def send_email_visitor(self):
        # send email to requesting email
        # this method is called with cleaned from data
        subject = "Ihre Nachricht an mentoki"
        to = [self.cleaned_data['email']]
        from_mail = '*****@*****.**'

        # prepare template
        context = {
            'name': self.cleaned_data['name'],
            'email': self.cleaned_data['email'],
            'message': self.cleaned_data['message'],
            'betreff': "Ihre Nachricht",
        }
        message = get_template('email/contact/to_customer.html').render(
            Context(context))
        to_customer = MailerMessage()
        to_customer.subject = "Ihre Nachricht an mentoki"
        to_customer.to_address = self.cleaned_data['email']
        to_customer.from_address = ContactForm.CONTACT_EMAIL
        to_customer.content = ContactForm.OUTGOING
        to_customer.html_content = message
        to_customer.reply_to = ContactForm.CONTACT_EMAIL
        to_customer.app = self.__module__
        to_customer.save()

    def send_email_self(self):
        """
        email is send to mentoki
        """
        context = {
            'name': self.cleaned_data['name'],
            'email': self.cleaned_data['email'],
            'message': self.cleaned_data['message'],
            'betreff': "Nachricht an mentoki",
        }
        message = get_template('email/contact/to_mentoki.html').render(
            Context(context))

        to_mentoki = MailerMessage()
        to_mentoki.subject = "Kontaktanfrage an mentoki"
        to_mentoki.to_address = ContactForm.CONTACT_EMAIL
        to_mentoki.from_address = self.cleaned_data['email']
        to_mentoki.content = ContactForm.INTERNAL
        to_mentoki.html_content = message
        to_mentoki.reply_to = self.cleaned_data['email']
        to_mentoki.app = self.__module__
        to_mentoki.save()
Example #16
0
class FloppyPasswordResetForm(PasswordResetForm):
    email = forms.EmailField(label=_("Email"), max_length=254)
Example #17
0
class StudentSignUpForm(UserCreationForm):
    # Declare user option fields to form
    first_name = forms.CharField(
        required=True,
        widget=forms.TextInput(attrs={'placeholder': 'First name'}))
    other_name = forms.CharField(
        required=True,
        widget=forms.TextInput(attrs={'placeholder': 'Other name'}))
    last_name = forms.CharField(
        required=True,
        widget=forms.TextInput(attrs={'placeholder': 'Surname'}))
    birth_place = forms.ChoiceField(required=True, choices=STATES)
    sex = forms.ChoiceField(required=True, choices=GENDER)
    birth_date = forms.DateField(required=True, widget=forms.DateInput)
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'placeholder': 'Enter email address'}),
        required=True)
    phone = forms.CharField(
        required=True,
        widget=forms.PhoneNumberInput(attrs={'placeholder': 'Mobile Number'}))
    address = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={'placeholder': 'House/Street/City/Town '}),
        max_length=100)
    faculty = forms.ModelChoiceField(queryset=Faculty.objects.all())

    # Add Extra Student options fields to form
    study_centre = forms.ModelChoiceField(queryset=Studycentre.objects.all(),
                                          required=False)
    programme = forms.ModelChoiceField(queryset=Programme.objects.all())
    department = forms.ModelChoiceField(queryset=Department.objects.all())
    level = forms.ChoiceField(choices=LEVEL, required=True)

    class Meta:
        model = User
        fields = (
            'first_name',
            'other_name',
            'last_name',
            'sex',
            'birth_place',
            'address',
            'phone',
            'email',
            'faculty',
            'department',
            'level',
            'programme',
            'study_centre',
            'birth_date',
        )

    # Add placeholders to UserCreationForm password fields
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password1'].widget.attrs.update(
            {'placeholder': 'Choose A Password'})
        self.fields['password2'].widget.attrs.update(
            {'placeholder': 'Verify Password'})

        # Filter Department choice by selected faculty
        self.fields['department'].queryset = Department.objects.none()
        self.fields['programme'].queryset = Programme.objects.none()

        for field_name in ['password1', 'password2']:
            self.fields[field_name].help_text = None

        if 'faculty' in self.data:
            try:
                faculty_id = int(self.data.get('faculty'))
                self.fields['department'].queryset = Department.objects.filter(
                    faculty_id=faculty_id).exclude(
                        name='General Studies').order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty department queryset
        elif self.instance.pk:
            self.fields[
                'department'].queryset = self.instance.faculty.department_set.order_by(
                    'name')

        if 'department' in self.data:
            try:
                department_id = int(self.data.get('department'))
                self.fields['programme'].queryset = Programme.objects.filter(
                    department_id=department_id).order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty department queryset
        elif self.instance.pk:
            self.fields[
                'programme'].queryset = self.instance.department.programme_set.order_by(
                    'name')

    # Check if inputted email has not been used by another user
    def clean_email(self):
        email = self.cleaned_data['email']
        check = User.objects.values('email')
        if email in check:
            msg = 'this email has been used!'
            self.add_error('email', msg)
        return email

    @transaction.atomic
    def save(self):
        user = super().save(commit=False)

        while True:
            gen_matric = 'stu' + str(random.randint(10000, 50000))
            if not Student.objects.filter(user__username=gen_matric).exists():
                user.username = gen_matric
                break

        user.is_student = True
        user.save()
        # retrieve student info from relevant form field
        study_centre = self.cleaned_data.get('study_centre')
        programme = self.cleaned_data.get('programme')
        department = self.cleaned_data.get('department')
        level = self.cleaned_data.get('level')
        # Create student object with user id
        Student.objects.create(user=user,
                               study_centre=study_centre,
                               programme=programme,
                               department=department,
                               level=level)
        return user
Example #18
0
class NewUserBaseForm(forms.Form):
    first_name = forms.CharField(
        max_length=30,
        label=_('First name'),
        widget=forms.TextInput(attrs={
            'placeholder': _('First Name'),
            'class': 'form-control'
        }))
    last_name = forms.CharField(
        max_length=30,
        label=_('Last name'),
        widget=forms.TextInput(attrs={
            'placeholder': _('Last Name'),
            'class': 'form-control'
        }))
    address = forms.CharField(
        max_length=300,
        required=False,
        label=_('Mailing Address'),
        help_text=
        _('Optional. Your address will not be displayed publicly and is only needed in case a public body needs to send you paper.'
          ),
        widget=forms.Textarea(
            attrs={
                'rows': '3',
                'class': 'form-control',
                'placeholder': _('Street, Post Code, City'),
            }))
    user_email = forms.EmailField(
        label=_('Email address'),
        max_length=75,
        help_text=_('Not public. The given address will '
                    'need to be confirmed.'),
        widget=forms.EmailInput(attrs={
            'placeholder': _('*****@*****.**'),
            'class': 'form-control'
        }))

    if HAVE_ORGANIZATION:
        organization = forms.CharField(
            required=False,
            label=_("Organization"),
            help_text=_(
                'Optional. Affiliation will be shown next to your name'),
            widget=forms.TextInput(attrs={
                'placeholder': _('Organization'),
                'class': 'form-control'
            }))

    if USER_CAN_HIDE_WEB:
        private = forms.BooleanField(
            required=False,
            label=_("Hide my name on the web"),
            help_text=mark_safe(
                _("If you check this, your name will still appear in requests to public bodies, but we will do our best to not display it publicly. However, we cannot guarantee your anonymity"
                  )))

    def __init__(self, *args, **kwargs):
        super(NewUserBaseForm, self).__init__(*args, **kwargs)
        if ALLOW_PSEUDONYM:
            self.fields["last_name"].help_text = mark_safe(
                _('<a target="_blank" href="{url}">You may use a pseudonym if you don\'t need to receive postal messages</a>.'
                  ).format(url=reverse("help-privacy") + '#pseudonym'))

    def clean_first_name(self):
        return self.cleaned_data['first_name'].strip()

    def clean_last_name(self):
        return self.cleaned_data['last_name'].strip()

    def clean_user_email(self):
        email = self.cleaned_data['user_email']
        user_model = get_user_model()
        try:
            user = user_model.objects.get(email=email)
        except user_model.DoesNotExist:
            pass
        else:
            if user.is_active:
                raise forms.ValidationError(
                    mark_safe(
                        _('This email address already has an account. <a href="%(url)s?simple&email=%(email)s" class="btn btn-warning target-small">Click here to login using that email address.</a>'
                          ) % {
                              'url': reverse("account-login"),
                              'email': email
                          }))
            else:
                raise forms.ValidationError(
                    _('This email address is already registered, but not yet confirmed! Please click on the confirmation link in the mail we send you.'
                      ))
        return email
Example #19
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['email'] = forms.EmailField()