class SignupForm(forms.Form): """ User Signup Form """ first_name = forms.CharField( label='Vorname', max_length=30, widget=forms.TextInput(attrs={ 'placeholder': 'Vorname', 'autofocus': 'autofocus' })) last_name = forms.CharField( label='Nachname', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Nachname'})) def signup(self, request, user): """ signup of users if an anonymous user was redirected to the signup form, it is memorized, what he wanted to buy in the "unfinshed_product_pk". :param request: :param user: :return: None """ user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if request.session.has_key('unfinished_checkout'): user.checkout_product_pk=\ request.session['unfinished_product_pk'] logger.info('Benutzer [%s] wird gespeichert mit Wunsch: [%s]' % (user, user.checkout_product_pk)) user.save()
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, ])
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 Meta: model = Contact fields = ('email', 'firstname', 'lastname') widgets = { 'lastname': forms.TextInput(attrs={'placeholder': _('Lastname')}), 'firstname': forms.TextInput(attrs={'placeholder': _('Firstname')}), 'email': forms.TextInput(attrs={ 'placeholder': _('Email'), 'required': 'required' }), }
class JobSearchForm(forms.Form): q = forms.CharField( label='What', required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'job title, keywords or tags', }), ) l = forms.CharField( label='Where', required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'job title, keywords or tags', }), ) is_visual_impairment_accepted = forms.BooleanField( label='visual disabilities', required=False, initial=False) is_hearing_impairment_accepted = forms.BooleanField( label='hearing disabilities', required=False, initial=False) is_motor_impairment_accepted = forms.BooleanField( label='motor disabilities', required=False, initial=False) def search(self, jobs): q = self.cleaned_data.get('q') if q: jobs = jobs.filter(title__icontains=q) l = self.cleaned_data.get('l') if l: jobs = jobs.filter(location__icontains=l) impairements_filter = {} for name in [ 'visual', 'hearing', 'motor', ]: impairment = 'is_{}_impairment_accepted'.format(name) value = self.cleaned_data.get(impairment) if value: impairements_filter[impairment] = value if impairements_filter: jobs = jobs.filter(**impairements_filter) return jobs
class ThreadForm(MessageForm): """ Formulaire de fil de discussion """ # Constantes SUBJECT_LENGTH_MIN = 1 # Champs supplémentaires subject = forms.CharField(max_length=48, required=False, widget=forms.TextInput()) recipient = forms.IntegerField(required=True, widget=forms.HiddenInput()) # Validation def clean_subject(self): """ Valider et renvoyer les données du champ sujet """ subject = self.data['subject'] if len(subject) < ThreadForm.SUBJECT_LENGTH_MIN: raise forms.ValidationError( _("Your subject must be at least {} characters long.").format( ThreadForm.SUBJECT_LENGTH_MIN)) return subject def clean_recipient(self): """ Valider et renvoyer les données du champ destinataire """ recipient = int(self.data['recipient']) if get_user_model().objects.get_or_none(id=recipient) is None: raise forms.ValidationError(_("The recipient does not exist.")) return get_user_model().objects.get(id=recipient)
class AddContactToGroupForm(BsForm): """form for adding a contact to a group""" group_name = forms.CharField( label=_("Group name"), widget=forms.TextInput( attrs={ 'size': 70, 'placeholder': _('start typing name and choose if exists') })) def __init__(self, contact, *args, **kwargs): self.contact = contact super(AddContactToGroupForm, self).__init__(*args, **kwargs) def clean_group_name(self): """validation""" name = self.cleaned_data['group_name'] request = RequestManager().get_request() if not can_create_group(request.user) and models.Group.objects.filter( name=name).count() == 0: raise ValidationError( ugettext("You are not allowed to create new groups")) if models.Group.objects.filter( name=name, contacts__id=self.contact.id).count() > 0: raise ValidationError( ugettext("The contact already belong to group {0}").format( name)) return name
class EscalationMessageForm(forms.Form): subject = forms.CharField( label=_("Subject"), max_length=230, widget=forms.TextInput(attrs={"class": "form-control"})) message = forms.CharField( widget=forms.Textarea(attrs={"class": "form-control"}), label=_("Your message"), ) def __init__(self, foirequest, *args, **kwargs): super(EscalationMessageForm, self).__init__(*args, **kwargs) self.foirequest = foirequest def clean_message(self): message = self.cleaned_data['message'] message = message.replace('\r\n', '\n').strip() empty_form = self.foirequest.get_escalation_message_form() if message == empty_form.initial['message'].strip(): raise forms.ValidationError( _('You need to fill in the blanks in the template!')) return message def clean(self): throttle_message = check_throttle(self.foirequest.user, FoiMessage) if throttle_message: raise forms.ValidationError(throttle_message) def save(self): self.foirequest.add_escalation_message(**self.cleaned_data)
class PostalReplyForm(PostalBaseForm): FIELD_ORDER = [ 'public_body', 'sender', 'date', 'subject', 'text', 'files', 'not_publishable' ] PUBLIC_BODY_LABEL = _('Sender public body') sender = forms.CharField( label=_("Sender name"), widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": _("Sender Name") }), required=True) not_publishable = forms.BooleanField( label=_("You are not allowed to publish some received documents"), initial=False, required=False, help_text= _('If the reply explicitly states that you are not allowed to publish some of the documents (e.g. due to copyright), check this.' )) def contribute_to_message(self, message): message.is_response = True message.sender_name = self.cleaned_data['sender'] message.sender_public_body = message.request.public_body message.not_publishable = self.cleaned_data['not_publishable'] return message
class ProjectForm(forms.ModelForm): topics = forms.ModelMultipleChoiceField( queryset=Topic.objects.all(), widget=forms.SelectMultiple(attrs={ 'inline': True, 'class': 'multiselect', }), required=False) events = forms.ModelMultipleChoiceField( queryset=Event.objects.all(), widget=forms.SelectMultiple(attrs={ 'inline': True, 'class': 'multiselect', }), required=False) technologies = forms.ModelMultipleChoiceField( queryset=Technology.objects.all(), widget=forms.SelectMultiple(attrs={ 'inline': True, 'class': 'multiselect', }), required=False) color = forms.CharField(widget=forms.TextInput(attrs={ 'inline': True, 'class': 'colorpicker', }), required=False) class Meta: model = Project fields = [ 'title', 'description', 'status', 'public_url', 'dev_url', 'screenshot', 'git_url', 'topics', 'events', 'technologies', 'color' ]
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")}), }
class LoginForm(forms.Form): """ Formulaire de connexion """ username = forms.CharField( required=True, widget=forms.TextInput(attrs={'placeholder': _("User name or email")}), label=_("Identifier")) password = forms.CharField( required=True, widget=forms.PasswordInput(attrs={'placeholder': _("Password")}), label=_("Password")) def __init__(self, *args, **kwargs): """ Initialiser le formulaire """ super(LoginForm, self).__init__(*args, **kwargs) self.request = kwargs.get('request', None) # Validation def clean(self): """ Valider et renvoyer les données du formulaire """ username = self.cleaned_data.get('username', None) password = self.cleaned_data.get('password', None) if username and password: User.sign(self.request, { 'username': username, 'password': password }, fake=True) return self.cleaned_data raise ValidationError( _("You must provide an username or email and a password."))
class Meta: model = Report fields = [ 'reporter_name', 'reporter_email', 'target', 'type', 'title', 'details' ] widgets = { 'reporter_name': forms.TextInput(), 'title': forms.TextInput(), } labels = { 'reporter_name': 'Your name', 'reporter_email': 'Your email', } help_texts = { 'reporter_email': "We'll only use this email to contact you about your report. We hate spam as much as you do." }
class Meta: model = Contact fields = ('gender', 'firstname', 'lastname', 'phone', 'mobile', 'email', 'address', 'address2', 'address3', 'zip_code') widgets = { 'lastname': forms.TextInput(attrs={ 'placeholder': _('Lastname'), 'required': 'required' }), 'firstname': forms.TextInput(attrs={'placeholder': _('Firstname')}), 'phone': forms.TextInput(attrs={'placeholder': _('Phone')}), 'email': forms.TextInput(attrs={ 'placeholder': _('Email'), 'required': 'required' }), 'zip_code': forms.TextInput(attrs={'placeholder': _('zip code')}), }
class Meta: """Define the form from model""" model = models.Group fields = ( 'name', 'description', 'background_color', 'fore_color', 'subscribe_form', ) # 'entities', 'contacts') widgets = { 'description': forms.TextInput( attrs={ 'placeholder': _('Enter a description for your group'), 'size': '80', }), 'name': forms.TextInput(attrs={ 'placeholder': _('Enter a name for your group'), 'size': '80', }), }
class NewTopicForm(forms.ModelForm): subject = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Add Subject'})) files = forms.FileField(required=False) class Meta: model = Topic fields = ['subject', 'course', 'message', 'files'] # Filter topic courses list for appointed lecturer def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super().__init__(*args, **kwargs) self.fields["course"].queryset = Course.objects.filter( lecturer=self.request.user.lecturer)
class ProfilesForm(forms.ModelForm): description = forms.CharField(label="Descriçao", required=False, widget=CKEditorWidget()) cep = br_forms.BRZipCodeField( label="CEP", required=False, widget=forms.TextInput(attrs={'placeholder': 'XXXXX-XXX'})) cel_phone = br_forms.BRPhoneNumberField( label="Celular", required=False, widget=forms.TextInput(attrs={'placeholder': 'XX-XXXX-XXXX'})) home_phone = br_forms.BRPhoneNumberField( label="Fixo", required=False, widget=forms.TextInput(attrs={'placeholder': 'XX-XXXX-XXXX'})) class Meta: model = Profile exclude = ['user'] class Media: css = {'all': ('css/profiles/profile_update.css', )}
class MakePublicBodySuggestionForm(forms.Form): public_body = forms.ModelChoiceField(label=_('Public body'), queryset=PublicBody.objects.all(), widget=PublicBodySelect) reason = forms.CharField( label=_("Please specify a reason why this is the right Public Body:"), widget=forms.TextInput(attrs={ "size": "40", "placeholder": _("Reason") }), required=False) def clean_public_body(self): public_body = self.cleaned_data['public_body'] self.public_body_object = public_body self.foi_law_object = public_body.default_law return public_body
class ActionForContactsForm(forms.ModelForm): """Create action for contacts""" date = forms.DateField(label=_("planned date"), required=False, widget=forms.TextInput()) time = forms.TimeField(label=_("planned time"), required=False) contacts = forms.CharField(widget=forms.HiddenInput()) class Meta: """create form from model""" model = Action fields = ('date', 'time', 'type', 'subject', 'in_charge', 'detail', 'planned_date', 'contacts', 'opportunity') def __init__(self, *args, **kwargs): initial = kwargs.get('initial') initial_contacts = '' if initial and 'contacts' in initial: initial_contacts = ';'.join( ['{0}'.format(c.id) for c in initial['contacts']]) initial.pop('contacts') super(ActionForContactsForm, self).__init__(*args, **kwargs) if initial_contacts: self.fields['contacts'].initial = initial_contacts self.fields['opportunity'].widget = OpportunityAutoComplete( attrs={ 'placeholder': _('Enter the name of an opportunity'), 'size': '80', 'class': 'colorbox' }) def get_contacts(self): """return contacts""" contact_ids = self.cleaned_data["contacts"].split(";") return Contact.objects.filter(id__in=contact_ids) def clean_planned_date(self): """validate planned date""" the_date = self.cleaned_data["date"] the_time = self.cleaned_data.get("time", None) if the_date: return datetime.combine(the_date, the_time or datetime.min.time()) return None
class PostalMessageForm(PostalBaseForm): FIELD_ORDER = [ 'public_body', 'recipient', 'date', 'subject', 'text', 'files' ] PUBLIC_BODY_LABEL = _('Receiving public body') recipient = forms.CharField( label=_("Recipient Name"), widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": _("Recipient Name") }), required=True) def contribute_to_message(self, message): message.is_response = False message.sender_user = message.request.user message.recipient = self.cleaned_data['recipient'] message.recipient_public_body = self.cleaned_data['public_body'] return message
class SendMessageForm(forms.Form): to = forms.TypedChoiceField( label=_("To"), choices=[], coerce=int, required=True, widget=forms.RadioSelect(attrs={"class": "form-control"})) subject = forms.CharField( label=_("Subject"), max_length=230, widget=forms.TextInput(attrs={"class": "form-control"})) message = forms.CharField( widget=forms.Textarea(attrs={"class": "form-control"}), label=_("Your message")) def __init__(self, foirequest, *args, **kwargs): super(SendMessageForm, self).__init__(*args, **kwargs) self.foirequest = foirequest choices = [(0, _("Default address of %(publicbody)s") % { "publicbody": foirequest.public_body.name })] choices.extend([ (m.id, m.reply_address_entry) for k, m in foirequest.possible_reply_addresses().items() ]) self.fields['to'].choices = choices if foirequest.law and foirequest.law.email_only: self.fields['send_address'] = forms.BooleanField( label=_("Send physical address"), help_text=(_( 'If the public body is asking for your post ' 'address, check this and we will append it to your message.' )), required=False) def clean(self): throttle_message = check_throttle(self.foirequest.user, FoiMessage) if throttle_message: raise forms.ValidationError(throttle_message) def save(self, user): if self.cleaned_data["to"] == 0: recipient_name = self.foirequest.public_body.name recipient_email = self.foirequest.public_body.email recipient_pb = self.foirequest.public_body else: message = list( filter(lambda x: x.id == self.cleaned_data["to"], list(self.foirequest.messages)))[0] recipient_name = message.sender_name recipient_email = message.sender_email recipient_pb = message.sender_public_body return self.foirequest.add_message(user, recipient_name, recipient_email, self.cleaned_data["subject"], self.cleaned_data['message'], recipient_pb=recipient_pb, send_address=self.cleaned_data.get( 'send_address', True))
class ActionForm(FormWithFieldsetMixin, BetterBsModelForm): """form for creating or editing action""" date = forms.DateField(label=_(u"planned date"), required=False, widget=forms.TextInput()) time = forms.TimeField(label=_(u"planned time"), required=False) end_date = forms.DateField(label=_(u"end date"), required=False, widget=forms.TextInput()) end_time = forms.TimeField(label=_(u"end time"), required=False) amount = forms.DecimalField(label=_("Amount"), required=False) class Meta: """form from model""" model = models.Action fields = ( 'type', 'subject', 'date', 'time', 'status', 'status2', 'in_charge', 'detail', 'amount', 'number', 'planned_date', 'end_date', 'end_time', 'end_datetime', 'opportunity' ) fieldsets = [ ('summary', { 'fields': [ 'subject', 'in_charge', 'date', 'time', 'planned_date', 'end_date', 'end_time', 'end_datetime', 'opportunity' ], 'legend': _('Summary') }), ('type', {'fields': ['type', 'status', 'status2', 'amount', 'number'], 'legend': _('Type')}), ('details', {'fields': ['detail'], 'legend': _('Details')}), ] help_texts = { 'amount': _('Amount is disabled when value is calculated'), } def __init__(self, *args, **kwargs): kwargs.pop('entity', None) instance = kwargs.get('instance', None) action_type = kwargs.pop('action_type', None) super(ActionForm, self).__init__(*args, **kwargs) self.title = u"" if instance: action_type = instance.type self.action_type = action_type is_amount_calculated = False if action_type: is_amount_calculated = action_type.is_amount_calculated self.calculated_amount = Decimal("0") for fieldset_name, fieldset_attrs in self.Meta.fieldsets: if fieldset_name == 'type': fieldset_attrs['legend'] = action_type.name break self.fields['type'].widget = forms.HiddenInput() self.fields['type'].initial = action_type if instance: self.title = ugettext(u"Edition {0}").format(action_type.name) else: self.title = ugettext(u"Creation {0}").format(action_type.name) else: self.title = ugettext(u"Edit action") if instance else ugettext(u"Create action") is_auto_generated = (action_type and action_type.number_auto_generated) or \ (instance and instance.type and instance.type.number_auto_generated) if is_auto_generated: self.fields['number'].widget.attrs['disabled'] = 'disabled' self.fields['number'].required = False self.fields['amount'].widget.attrs['step'] = 'any' if is_amount_calculated: self.fields['amount'].widget.attrs['disabled'] = 'disabled' self.is_amount_calculated = is_amount_calculated if action_type and action_type.allowed_status.count(): # let javascript disable the blank value if default_status choices = [('', "---------")] allowed_status = action_type.allowed_status.all() if instance and instance.frozen: allowed_status = allowed_status.filter(allowed_on_frozen=True) self.fields['status'].choices = choices + [ (status.id, status.name) for status in allowed_status ] if action_type.default_status: self.fields['status'].initial = action_type.default_status.id else: self.fields['status'].initial = '' if action_type and action_type.allowed_status2.count(): # let javascript disable the blank value if default_status2 allowed_status2 = action_type.allowed_status2.all() if instance and instance.frozen: allowed_status2 = allowed_status2.filter(allowed_on_frozen=True) choices = [('', "---------")] self.fields['status2'].choices = choices + [ (status.id, status.name) for status in allowed_status2 ] if action_type.default_status2: self.fields['status2'].initial = action_type.default_status2.id else: self.fields['status2'].initial = '' else: self.fields['status2'].widget = forms.HiddenInput() self.fields['opportunity'].widget = forms.HiddenInput() self.fields['detail'].widget = forms.Textarea(attrs={'placeholder': _('enter details'), 'cols': '72'}) self._init_dt_field("planned_date", "date", "time") self._init_dt_field("end_datetime", "end_date", "end_time") def _init_dt_field(self, dt_field, date_field, time_field): """init datetime fields""" self.fields[dt_field].widget = CalcHiddenInput() the_datetime = getattr(self.instance, dt_field) if self.instance else self.fields[dt_field].initial if the_datetime: self.fields[date_field].initial = the_datetime.date() if settings.USE_TZ: utc_dt = the_datetime.replace(tzinfo=timezone.utc) loc_dt = utc_dt.astimezone(timezone.get_current_timezone()) self.fields[time_field].initial = loc_dt.time() else: self.fields[time_field].initial = the_datetime.time() is_frozen = self.instance.frozen if self.instance else False if is_frozen: self.fields[date_field].widget.attrs['disabled'] = 'disabled' self.fields[time_field].widget.attrs['disabled'] = 'disabled' def clean_status(self): """status validation""" type_of = self.cleaned_data.get('type') or self.action_type status = self.cleaned_data['status'] if type_of: allowed_status = ([] if type_of.default_status else [None]) + list(type_of.allowed_status.all()) if len(allowed_status) > 0 and status not in allowed_status: raise ValidationError(ugettext(u"This status can't not be used for this action type")) else: if status: raise ValidationError(ugettext(u"Please select a type before defining the status")) return status def clean_status2(self): """status validation""" type_of = self.cleaned_data['type'] status = self.cleaned_data['status2'] if type_of: allowed_status = ([] if type_of.default_status2 else [None]) + list(type_of.allowed_status2.all()) if len(allowed_status) > 0 and status not in allowed_status: raise ValidationError(ugettext(u"This status can't not be used for this action type")) else: if status: raise ValidationError(ugettext(u"Please select a type before defining the status")) return status def clean_planned_date(self): """planned date validation""" the_date = self.cleaned_data.get("date", None) the_time = self.cleaned_data.get("time", None) if the_date: return datetime.combine(the_date, the_time or datetime.min.time()) return None def clean_time(self): """time validation""" the_date = self.cleaned_data.get("date", None) the_time = self.cleaned_data.get("time", None) if the_time and not the_date: raise ValidationError(_(u"You must set a date")) return the_time def clean_end_date(self): """end date validation""" date1 = self.cleaned_data.get("date", None) date2 = self.cleaned_data.get("end_date", None) if date2: start_dt = self.cleaned_data["planned_date"] if not start_dt: raise ValidationError(_(u"The planned date is not defined")) if date1 > date2: raise ValidationError(_(u"The end date must be after the planned date")) return date2 def clean_end_time(self): """end time validation""" date1 = self.cleaned_data.get("date", None) date2 = self.cleaned_data.get("end_date", None) time1 = self.cleaned_data.get("time", None) time2 = self.cleaned_data.get("end_time", None) if time2: if time2 and not date2: raise ValidationError(_(u"You must set a end date")) if date1 == date2 and (time1 or datetime.min.time()) >= time2: raise ValidationError(_(u"The end time must be after the planned time")) elif time1: if date1 == date2 and time1 >= datetime.min.time(): raise ValidationError(_(u"The end time must be set")) return time2 def clean_end_datetime(self): """clean end datetime""" end_date = self.cleaned_data.get("end_date", None) end_time = self.cleaned_data.get("end_time", None) if end_date: return datetime.combine(end_date, end_time or datetime.min.time()) return None def clean_amount(self): if self.is_amount_calculated: return self.calculated_amount else: return self.cleaned_data['amount'] def save(self, *args, **kwargs): return super(ActionForm, self).save(*args, **kwargs)
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")}), }
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
class QuickSearchForm(BsForm): """Quick search form which is included in the menu""" text = forms.CharField( required=True, widget=forms.TextInput(attrs={'placeholder': _(u'Quick search')}) )
class PostalBaseForm(AttachmentSaverMixin, forms.Form): scan_help_text = mark_safe( _("Uploaded scans can be PDF, JPG or PNG. Please make sure to <strong>redact/black out all private information concerning you</strong>." )) public_body = forms.ModelChoiceField(label=_('Public body'), queryset=PublicBody.objects.all(), widget=PublicBodySelect) date = forms.DateField( widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": _('mm/dd/YYYY') }), label=_("Send Date"), help_text=_("Please give the date the reply was sent."), localize=True) subject = forms.CharField( label=_("Subject"), required=False, max_length=230, widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": _("Subject") })) text = forms.CharField( label=_("Letter"), widget=forms.Textarea(attrs={ "placeholder": _("Letter text"), "class": "form-control" }), required=False, help_text= _("The text can be left empty, instead you can upload scanned documents." )) files = forms.FileField(label=_("Scanned Letter"), required=False, validators=[validate_upload_document], help_text=scan_help_text, widget=forms.FileInput(attrs={'multiple': True})) FIELD_ORDER = ['public_body', 'date', 'subject', 'text', 'files'] def __init__(self, *args, **kwargs): self.foirequest = kwargs.pop('foirequest') super(PostalBaseForm, self).__init__(*args, **kwargs) self.fields['public_body'].label = self.PUBLIC_BODY_LABEL self.fields['public_body'].initial = self.foirequest.public_body self.order_fields(self.FIELD_ORDER) def clean_date(self): date = self.cleaned_data['date'] now = timezone.now().date() if date > now: raise forms.ValidationError( _("Your reply date is in the future, that is not possible.")) return date def clean_files(self): if 'files' not in self.files: return self.cleaned_data['files'] files = self.files.getlist('files') names = set() for file in files: validate_upload_document(file) name = self.make_filename(file.name) if name in names: # FIXME: dont make this a requirement raise forms.ValidationError( _('Upload files must have distinct names')) names.add(name) return self.cleaned_data['files'] def clean(self): cleaned_data = self.cleaned_data text = cleaned_data.get("text") if 'files' in self.files: files = self.files.getlist('files') else: files = None if not (text or files): raise forms.ValidationError( _("You need to provide either the letter text or a scanned document." )) return cleaned_data def save(self): foirequest = self.foirequest message = FoiMessage( request=foirequest, is_postal=True, ) # TODO: Check if timezone support is correct date = datetime.datetime.combine(self.cleaned_data['date'], datetime.time()) message.timestamp = timezone.get_current_timezone().localize(date) message.subject = self.cleaned_data.get('subject', '') message.subject_redacted = message.redact_subject()[:250] message.plaintext = "" if self.cleaned_data.get('text'): message.plaintext = self.cleaned_data.get('text') message.plaintext_redacted = message.get_content() message = self.contribute_to_message(message) message.save() foirequest.last_message = message.timestamp foirequest.status = 'awaiting_classification' foirequest.save() foirequest.add_postal_reply.send(sender=foirequest) if self.cleaned_data.get('files'): self.save_attachments(self.files.getlist('files'), message) return message
class BankTransactionListForm(forms.Form): label = forms.CharField( max_length=255, required=False, widget=forms.TextInput(attrs={ 'placeholder': ugettext_lazy('Label'), })) date_start = forms.DateField( required=False, widget=Datepicker(attrs={ 'placeholder': ugettext_lazy('Date start'), }), ) date_end = forms.DateField( required=False, widget=Datepicker(attrs={ 'placeholder': ugettext_lazy('Date end'), }), ) amount_min = forms.DecimalField( max_digits=10, decimal_places=2, localize=True, required=False, widget=forms.NumberInput( attrs={ 'placeholder': ugettext_lazy('Minimum amount'), }), ) amount_max = forms.DecimalField( max_digits=10, decimal_places=2, localize=True, required=False, widget=forms.NumberInput( attrs={ 'placeholder': ugettext_lazy('Maximum amount'), }), ) status = forms.ChoiceField( choices=(('', ugettext_lazy('Status?')), ) + BankTransaction.STATUSES, initial='', required=False, ) reconciled = forms.NullBooleanField(required=False) tags = forms.ModelMultipleChoiceField( queryset=BankTransactionTag.objects.none(), required=False) operation = forms.ChoiceField( choices=(), required=False, ) def __init__(self, user, bt_ids, submit, *args, **kwargs): super(BankTransactionListForm, self).__init__(*args, **kwargs) self.fields['tags'].queryset = ( BankTransactionTag.objects.get_user_tags_queryset(user)) self.fields['reconciled'].widget.choices[0] = ('1', _('Reconciled?')) for pk in bt_ids: self.fields['banktransaction_' + str(pk)] = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'data-id': pk})) choices = () if user.has_perm('banktransactions.change_banktransaction'): choices += ( ('reconcile', _('Reconcile')), ('unreconcile', _('Unreconcile')), ) if user.has_perm('banktransactions.delete_banktransaction'): choices += (('delete', _('Delete')), ) if choices: self.fields['operation'].choices = choices self._submit = submit def clean(self): cleaned_data = super(BankTransactionListForm, self).clean() if self._submit == 'filter': date_start = cleaned_data.get('date_start') date_end = cleaned_data.get('date_end') if date_start and date_end and date_start > date_end: raise forms.ValidationError( _("Date start could not be greater than date end."), code='date_start_greater', ) amount_min = cleaned_data.get('amount_min', None) amount_max = cleaned_data.get('amount_max', None) if (amount_min is not None and amount_max is not None and amount_min > amount_max): raise forms.ValidationError( _("Minimum amount could not be greater than maximum " "amount."), code='amount_min_greater', ) if self._submit == 'action' and cleaned_data['operation']: ids = set() for name, value in cleaned_data.items(): if name.startswith('banktransaction_') and value: ids.add(int(name[len('banktransaction_'):])) if not ids: raise forms.ValidationError( _('To apply operations, you need to select some bank ' 'transactions.'), code='no_id', ) cleaned_data['banktransactions'] = ids return cleaned_data
class RequestForm(forms.Form): public_body = forms.CharField( widget=PublicBodySelect, label=_("Search for a topic or a public body:"), required=False) subject = forms.CharField( label=_("Subject"), max_length=230, widget=forms.TextInput(attrs={ 'placeholder': _("Subject"), "class": "form-control" })) body = forms.CharField( label=_("Body"), widget=forms.Textarea( attrs={ 'placeholder': _("Specify your request here..."), "class": "form-control" })) full_text = forms.BooleanField( required=False, initial=False, label=_("Don't wrap in template"), widget=forms.CheckboxInput(attrs={'tabindex': '-1'})) public = forms.BooleanField( required=False, initial=True, label=_("This request is public."), help_text=_( "If you don't want your request to be public right now," " uncheck this. You can always decide to make it public later.")) reference = forms.CharField(widget=forms.HiddenInput, required=False) redirect_url = forms.CharField(widget=forms.HiddenInput, required=False) hide_public = forms.BooleanField(widget=forms.HiddenInput, initial=False, required=False) hide_similar = forms.BooleanField(widget=forms.HiddenInput, initial=False, required=False) def __init__(self, user=None, list_of_laws=(), default_law=None, hide_law_widgets=True, **kwargs): super(RequestForm, self).__init__(**kwargs) self.user = user self.list_of_laws = list_of_laws self.indexed_laws = dict([(l.pk, l) for l in self.list_of_laws]) self.default_law = default_law self.fields["public_body"].widget.set_initial_jurisdiction( kwargs.get('initial', {}).pop('jurisdiction', None)) self.fields["public_body"].widget.set_initial_search( kwargs.get('initial', {}).pop('public_body_search', None)) self.fields["law"] = forms.ChoiceField( label=_("Information Law"), required=False, widget=forms.Select if not hide_law_widgets else forms.HiddenInput, initial=default_law.pk, choices=((l.pk, l.name) for l in list_of_laws)) def laws_to_json(self): return json.dumps( dict([(l.id, l.as_dict()) for l in self.list_of_laws])) def clean_public_body(self): pb = self.cleaned_data['public_body'] if pb == "new": if not new_publicbody_allowed: raise forms.ValidationError( _("You are not allowed to create a new public body")) elif pb == "": if not publicbody_empty: raise forms.ValidationError( _("You must specify a public body")) pb = None else: try: pb_pk = int(pb) except ValueError: raise forms.ValidationError(_("Invalid value")) try: public_body = PublicBody.objects.get(pk=pb_pk) except PublicBody.DoesNotExist: raise forms.ValidationError(_("Invalid value")) self.public_body_object = public_body self.foi_law_object = public_body.default_law return pb public_body_object = None def clean_reference(self): ref = self.cleaned_data['reference'] if not ref: return '' try: kind, value = ref.split(':', 1) except ValueError: return '' try: return '%s:%s' % (kind, value) except ValueError: return '' def clean_law_for_public_body(self, public_body): law = self.clean_law_without_public_body() if law is None: return None if law.jurisdiction.id != public_body.jurisdiction.id: self._errors["law"] = self.error_class( [_("Invalid Information Law")]) return None return law def clean_law_without_public_body(self): try: law = self.cleaned_data['law'] law = self.indexed_laws[int(law)] except (ValueError, KeyError): self._errors["law"] = self.error_class( [_("Invalid Information Law")]) return None return law def clean(self): cleaned = self.cleaned_data public_body = cleaned.get("public_body") if public_body is not None and (public_body != "new" and public_body != ""): self.foi_law = self.clean_law_for_public_body( self.public_body_object) else: self.foi_law = self.clean_law_without_public_body() throttle_message = check_throttle(self.user, FoiRequest) if throttle_message: raise forms.ValidationError(throttle_message) return cleaned
class Meta: model = Message widgets = {'text': forms.TextInput(attrs={'size': 80})} fields = ['thread', 'author', 'text', 'deleted']
class UserRegistrationForm(ModelFormWithCity, SubscriptionTypeFormMixin): """A form for creating a new account on a website""" email = EmailField(required=True, label=_("Email"), widget=forms.TextInput()) password1 = forms.CharField(required=True, widget=forms.PasswordInput(), label=_("Password")) password2 = forms.CharField(required=True, widget=forms.PasswordInput(), label=_("Repeat your password")) entity_type = forms.ChoiceField(required=False, widget=forms.Select()) entity = forms.CharField( required=False, widget=forms.TextInput(attrs={'placeholder': _('Name of the entity')})) groups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), label='', required=False) accept_termofuse = forms.BooleanField( label=_('Accept terms of use'), help_text=_("Check for accepting the terms of use")) city = forms.CharField( required=False, label=_('City'), widget=CityAutoComplete(attrs={ 'placeholder': _('Enter a city'), 'size': '80' })) class Meta: model = ContactProfile fields = ('email', 'password1', 'password2', 'entity_type', 'entity', 'gender', 'firstname', 'lastname', 'phone', 'mobile', 'address', 'zip_code', 'city', 'cedex', 'country', 'groups', 'accept_termofuse') def __init__(self, *args, **kwargs): super(UserRegistrationForm, self).__init__(*args, **kwargs) if 'gender' in self.fields: # do not display Mrs and Mr self.fields['gender'].choices = [ (Contact.GENDER_NOT_SET, _('Gender')), (Contact.GENDER_MALE, ugettext('Mr')), (Contact.GENDER_FEMALE, ugettext('Mrs')), ] if 'entity_type' in self.fields: self.fields['entity_type'].choices = [ (0, ugettext('Individual')) ] + [(et.id, et.name) for et in EntityType.objects.filter(subscribe_form=True)] if not has_entity_on_registration_form(): self.fields['entity_type'].inital = 0 self.fields['entity_type'].widget = forms.HiddenInput() self.fields['entity'].widget = forms.HiddenInput() termsofuse_url = get_registration_accept_terms_of_use_link() if 'accept_termofuse' in self.fields and termsofuse_url: self.fields['accept_termofuse'].label = mark_safe( ugettext('Accept <a href="{0}">terms of use</a>').format( termsofuse_url)) self._add_subscription_types_field() def clean_entity(self, ): entity_type = self.cleaned_data.get('entity_type', None) entity = self.cleaned_data['entity'] if entity_type: if not entity: raise ValidationError( _("{0}: Please enter a name".format(entity_type))) return entity def clean_entity_type(self): try: entity_type_id = int(self.cleaned_data['entity_type'] or 0) except ValueError: raise ValidationError(ugettext('Invalid entity type')) if entity_type_id: try: return EntityType.objects.get(id=entity_type_id) except EntityType.DoesNotExist: raise ValidationError(ugettext('Unknown entity type')) return None def clean(self, *args, **kwargs): password1 = self.cleaned_data.get('password1', "") password2 = self.cleaned_data.get('password2', "") if password1 and (password1 != password2): raise forms.ValidationError(ugettext('Passwords are not the same')) return super(UserRegistrationForm, self).clean(*args, **kwargs) def save(self, commit=True): if get_registration_version() >= "2.0.0": # Django registration 2.0 # The registration form should return a user email = self.cleaned_data["email"] username = email[:30] user = User.objects.create(username=username, email=email, is_active=False) password = self.cleaned_data.get('password1', "") user.set_password(password) return user else: # Django registration 1.0 return super(UserRegistrationForm, self).save(commit)