class N400AboutYouContinued(forms.Form): # "Current residential address" residential_address_street = forms.CharField(label="Current residential address street number and name", required=False) residential_address_apt = forms.CharField(label="Apartment or floor number (if applicable)", required=False) residential_address_city = forms.CharField(label="City", required=False) residential_address_state = forms.ChoiceField(choices=STATES, label="State", required=False) # @maybe: Refactor as a USStateSelect. residential_address_zip = USZipCodeField(label="ZIP code", required=False) # @maybe: Refactor these as CountryField()s. # Docs: https://pypi.python.org/pypi/django-countries#countryselectwidget residential_address_country = forms.CharField(label="Country, if outside the U.S.", required=False) # dates_of_residence = forms.CharField(label="Dates of residence (ex: from MM/DD/YYYY to present", required=False) # Is your mailing address different than your residential address? # or: If you have a different mailing address: # mailing_address_street = forms.CharField(label="Mailing address street number and name", required=False) # mailing_address_apt = forms.CharField(label="Apartment or floor number (if applicable)", required=False) # mailing_address_city = forms.CharField(label="City", required=False) # mailing_address_state = forms.ChoiceField(choices=STATES, label="State", required=False) # @maybe: Refactor as a USStateSelect. # mailing_address_zip = USZipCodeField(label="ZIP code", required=False) email = forms.EmailField(label="Email address", required=False) # @todo: Tweak this to allow for non-U.S. phone numbers. Add country code field. phone_primary = USPhoneNumberField(label="Primary phone number", required=False) phone_additional = USPhoneNumberField(label="Additional phone number", required=False) how_to_contact = forms.ChoiceField(label='How would you like us to contact you?', choices=CONTACT_OPTIONS, required=False) occupation = forms.CharField(label="Occupation", required=False) employer_name = forms.CharField(label="Name of your current employer or school", required=False)
class UserContactForm(FormUnrestrictedOtherUser, FormWithTagInitialValues): """ Base for contact form """ first_name = StrippedCharField(length=25, max_length=64) last_name = StrippedCharField(length=30, max_length=64) e_mail = forms.EmailField() phone_day = USPhoneNumberField(required=False) phone_cell = USPhoneNumberField(required=False) receive_txt_message = forms.TypedChoiceField(coerce=lambda x: x =='True', choices=((True, 'Yes'),(False, 'No')), widget=forms.RadioSelect) address_street = StrippedCharField(required=False, length=40, max_length=100) address_city = StrippedCharField(required=False, length=20, max_length=50) address_state = forms.ChoiceField(required=False, choices=zip(_states,_states), widget=forms.Select(attrs={'class': 'input-mini'})) address_zip = StrippedCharField(required=False, length=5, max_length=5, widget=forms.TextInput(attrs={'class': 'input-small'})) address_postal = forms.CharField(required=False, widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): super(UserContactForm, self).__init__(*args, **kwargs) if not Tag.getBooleanTag('request_student_phonenum', default=True): del self.fields['phone_day'] if not Tag.getBooleanTag('text_messages_to_students') or not self.user.isStudent(): del self.fields['receive_txt_message'] if not self.user.isTeacher() or Tag.getBooleanTag('teacher_address_required', default = True): self.fields['address_street'].required = True self.fields['address_city'].required = True self.fields['address_state'].required = True self.fields['address_zip'].required = True def clean(self): super(UserContactForm, self).clean() if self.user.isTeacher() or Tag.getBooleanTag('request_student_phonenum', default=True): if self.cleaned_data.get('phone_day','') == '' and self.cleaned_data.get('phone_cell','') == '': raise forms.ValidationError("Please provide either a day phone or cell phone number in your personal contact information.") if self.cleaned_data.get('receive_txt_message', None) and self.cleaned_data.get('phone_cell','') == '': raise forms.ValidationError("Please specify your cellphone number if you ask to receive text messages.") return self.cleaned_data
class AgencyForm(forms.ModelForm): """A form for an Agency""" email = FullEmailField(required=False) phone = USPhoneNumberField(required=False) fax = USPhoneNumberField(required=False) def save(self, *args, **kwargs): """Save email, phone, fax, and address models on save""" agency = super(AgencyForm, self).save(*args, **kwargs) if self.cleaned_data['email']: email_address = EmailAddress.objects.fetch(self.cleaned_data['email']) AgencyEmail.objects.create( agency=agency, email=email_address, request_type='primary', email_type='to', ) if self.cleaned_data['phone']: phone_number, _ = PhoneNumber.objects.update_or_create( number=self.cleaned_data['phone'], defaults={'type': 'phone'}, ) AgencyPhone.objects.create( agency=agency, phone=phone_number, ) if self.cleaned_data['fax']: fax_number, _ = PhoneNumber.objects.update_or_create( number=self.cleaned_data['fax'], defaults={'type': 'fax'}, ) AgencyPhone.objects.create( agency=agency, phone=fax_number, request_type='primary', ) if self.cleaned_data['address']: address, _ = Address.objects.get_or_create( address=self.cleaned_data['address'], ) AgencyAddress.objects.create( agency=agency, address=address, request_type='primary', ) class Meta: # pylint: disable=too-few-public-methods model = Agency fields = ['name', 'aliases', 'address', 'email', 'url', 'phone', 'fax'] labels = { 'aliases': 'Alias', 'url': 'Website', 'address': 'Mailing Address' } help_texts = { 'aliases': ('An alternate name for the agency, ' 'e.g. "CIA" is an alias for "Central Intelligence Agency".') }
class EmergContactForm(FormUnrestrictedOtherUser): """ Contact form for emergency contacts """ emerg_first_name = StrippedCharField(length=25, max_length=64) emerg_last_name = StrippedCharField(length=30, max_length=64) emerg_e_mail = forms.EmailField(required=False) emerg_phone_day = USPhoneNumberField() emerg_phone_cell = USPhoneNumberField(required=False) emerg_address_street = StrippedCharField(length=40, max_length=100) emerg_address_city = StrippedCharField(length=20, max_length=50) emerg_address_state = forms.ChoiceField( choices=zip(_states, _states), widget=forms.Select(attrs={'class': 'input-mini'})) emerg_address_zip = StrippedCharField( length=5, max_length=5, widget=forms.TextInput(attrs={'class': 'input-small'})) emerg_address_postal = forms.CharField(required=False, widget=forms.HiddenInput()) def clean(self): super(EmergContactForm, self).clean() if self.cleaned_data.get('emerg_phone_day', '') == '' and self.cleaned_data.get( 'emerg_phone_cell', '') == '': raise forms.ValidationError( "Please provide either a day phone or cell phone for your emergency contact." ) return self.cleaned_data
class AddEditMemberForm(forms.Form): """ A form for adding a member user to the current Account """ first_name = forms.CharField(max_length=30, error_messages={'required': 'First name is required.'}) last_name = forms.CharField(max_length=30, error_messages={'required': 'Last name is required.'}) email = forms.EmailField(error_messages={'required': 'Email address is required.'}) phone = USPhoneNumberField(error_messages={'required': 'Phone number is required.'}) mobile_phone = USPhoneNumberField(required=False, error_messages={}) date_of_birth = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y'), input_formats=('%m/%d/%Y', '%m/%d/%y',), error_messages={'required': 'Date of Birth is required.'}) weight = forms.ChoiceField(widget=forms.Select, choices=UserProfile.WEIGHT_RANGE_CHOICES) ship_street_1 = forms.CharField(max_length=128, required=False) ship_street_2 = forms.CharField(max_length=128, required=False) ship_city = forms.CharField(max_length=64, required=False) ship_state = forms.ChoiceField(required=False, choices=STATE_CHOICES, initial='TX') ship_postal_code = USZipCodeField(required=False) member_groups = forms.ModelMultipleChoiceField(queryset=Group.objects.filter(name__in=['Corporate Account Admin', 'Coordinator', 'Account Member']), widget=forms.CheckboxSelectMultiple) payment_method = forms.ChoiceField(required=False, choices=(),initial='') def __init__(self, user, *args, **kwargs): super(AddEditMemberForm, self).__init__(*args, **kwargs) self.user = user pms = user.account.get_all_payment_methods() payment_choices = [] for pm in pms: if pm['nickname'] is not None: txt = pm['text'] + " (" + pm['nickname'] + ")" else: txt = pm['text'] payment_choices.append( (pm['id'], txt)) self.fields['payment_method'].choices = payment_choices def clean_email(self): """ Check to see if this email already belongs to someone else. """ email = self.cleaned_data.get('email') if User.objects.filter(email=email).exclude(id=self.user.id).exists(): self._errors['email'] = self.error_class(['This email has already been used.']) return email def clean_payment_methods(self): groups = self.cleaned_data.get('member_groups') payment_method = self.cleaned_data.get('payment_method') notcoord = groups.exclude(name='Coordinator').first() if notcoord and not payment_method: self._errors['payment_method'] = self.error_class(['You must select a payment method.']) return payment_method
class GuardContactForm(FormUnrestrictedOtherUser): """ Contact form for guardians """ guard_first_name = StrippedCharField(length=25, max_length=64) guard_last_name = StrippedCharField(length=30, max_length=64) guard_e_mail = forms.EmailField(required=False) guard_phone_day = USPhoneNumberField() guard_phone_cell = USPhoneNumberField(required=False) def clean(self): super(GuardContactForm, self).clean() if self.cleaned_data.get('guard_phone_day','') == '' and self.cleaned_data.get('guard_phone_cell','') == '': raise forms.ValidationError("Please provide either a day phone or cell phone for your parent/guardian.") return self.cleaned_data
class ResetRequestForm(forms.Form): email = forms.EmailField(label="Email Address", required=False) cell = USPhoneNumberField(label="-OR- Cell #", required=False) # Verify that they did not use an @pdx.edu address in the external email field. def clean_email(self): email = self.cleaned_data['email'] if email.endswith('@pdx.edu'): raise forms.ValidationError( "Can not reset with an @pdx.edu address. Please use your personal email address." ) return email def clean(self): cleaned_data = super(ResetRequestForm, self).clean() email = cleaned_data.get("email") cell = cleaned_data.get("cell") if email == '' and cell == '': raise forms.ValidationError( 'You must provide either an email or cell # to send a reset token to.' ) return cleaned_data
class ReminderForm(forms.Form): """reminder form.""" send_email = forms.BooleanField(required=False) email = forms.EmailField(required=False, label="Email Address") send_text = forms.BooleanField(required=False) email_advance = forms.ChoiceField( choices=REMINDER_TIME_CHOICES, label="Send reminder how far in advance?") text_number = USPhoneNumberField(required=False, label="Mobile phone number") text_carrier = forms.ChoiceField(choices=TextReminder.TEXT_CARRIERS, required=False, label="Carrier") text_advance = forms.ChoiceField(choices=REMINDER_TIME_CHOICES, label="Send reminder how far in advance?") def clean(self): """validate form.""" cleaned_data = self.cleaned_data send_email = cleaned_data.get("send_email") email = None if "email" in cleaned_data: email = cleaned_data.get("email") if send_email and (not email or len(email) == 0): raise forms.ValidationError("A valid email address is required.") send_text = cleaned_data.get("send_text") number = None if "text_number" in cleaned_data: number = cleaned_data.get("text_number") if send_text and (not number or len(number) == 0): raise forms.ValidationError("A valid phone number is required.") return cleaned_data
class CorporateSignUpForm(forms.Form): """ Form to enter initial sign-up contact information for a company account """ first_name = forms.CharField(max_length=30, error_messages={'required': 'First name is required.'}) last_name = forms.CharField(max_length=30, error_messages={'required': 'Last name is required.'}) email = forms.EmailField(error_messages={'required': 'Email address is required.'}) company = forms.CharField(max_length=30, error_messages={'required': 'Company name is required.'}) phone = USPhoneNumberField(required=False, error_messages={}) def clean_email(self): """ Check to see if this email is already signed up. """ email = self.cleaned_data.get('email') no_no_list = ( 'aol.com', 'hotmail.com', 'gmail.com', 'yahoo.com' ) no_no_re = re.compile('|.+'.join(no_no_list)) if re.search(no_no_re, email): self._errors['email'] = self.error_class(['Please enter your company email address.']) if User.objects.filter(email=email).exists(): self._errors['email'] = self.error_class(['This email has already been used.']) return email
class InitiateRegistrationForm(BetterForm): error_messages = { "duplicate_email": "A user with that email address already exists", "duplicate_phone_number": "A user with that phone number address already exists", } email = forms.EmailField() phone_number = USPhoneNumberField( help_text="Must be able to receive SMS messages. Normal rates apply.", ) def clean_email(self): User = get_user_model() email = self.cleaned_data['email'] try: User.objects.get(email__iexact=email) except User.DoesNotExist: return email else: raise forms.ValidationError(self.error_messages['duplicate_email']) def clean_phone_number(self): phone_number = self.cleaned_data['phone_number'] try: User.objects.get(_profile__phone_number=phone_number) except User.DoesNotExist: return phone_number else: raise forms.ValidationError(self.error_messages['duplicate_phone_number'])
def test_PhoneNumberFormField_deprecated(self): with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter("always") AUPhoneNumberField() BEPhoneNumberField() BRPhoneNumberField() CAPhoneNumberField() CHPhoneNumberField() CNPhoneNumberField() CNCellNumberField() DKPhoneNumberField() ESPhoneNumberField() FRPhoneNumberField() GRPhoneNumberField() GRMobilePhoneNumberField() HKPhoneNumberField() HRPhoneNumberField() IDPhoneNumberField() ILMobilePhoneNumberField() INPhoneNumberField() ISPhoneNumberField() ITPhoneNumberField() NLPhoneNumberField() NOPhoneNumberField() NZPhoneNumberField() PKPhoneNumberField() PTPhoneNumberField() ROPhoneNumberField() SGPhoneNumberField() SIPhoneNumberField() TRPhoneNumberField() USPhoneNumberField() self.assertTrue(all(w.category is RemovedInLocalflavor20Warning for w in recorded))
class ResourceForm(ModelForm): """Form for editing and creating resources.""" state = forms.ChoiceField(choices=[('Washington', 'Washington')], initial='Washington', disabled=True, label='State') street = forms.CharField(required=False) zip_code = USZipCodeField(required=False) phone_number = USPhoneNumberField(required=False) fax_number = USPhoneNumberField(required=False) website = forms.URLField(initial='http://', required=False) class Meta: model = Resource fields = [ 'name', 'description', 'street', 'city', 'state', 'zip_code', 'website', 'phone_number', 'fax_number', 'email', 'image', 'gender', 'languages', 'services', 'lower_age', 'upper_age', 'us_citizens_only', 'sober_only', 'case_managers', 'open_24_hours', 'pets', 'accepts_sex_offender_records', 'accepts_criminal_records', 'accepts_incarcerated', 'family_friendly', 'orca_cards_available' ] widgets = { 'languages': forms.CheckboxSelectMultiple(), 'services': forms.CheckboxSelectMultiple() } labels = { 'languages': 'Languages spoken:', 'services': 'Select all services your organization provides.', 'gender': 'Gender restrictions?', 'lower_age': 'Lower age limit', 'upper_age': 'Upper age limit', 'pets': 'Pets allowed' } def clean(self): """Overridden clean method for validation of the age inputs.""" if self.cleaned_data['upper_age'] <= self.cleaned_data['lower_age']: raise ValidationError( 'Invalid entries for lower and upper age ranges.') return self.cleaned_data
class AccountSettingsForm(forms.Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(AccountSettingsForm, self).__init__(*args, **kwargs) username = forms.CharField(max_length=30, label=_('User Name')) email = forms.EmailField(max_length=255, label=_('Email')) first_name = forms.CharField(max_length=100, label=_('First Name')) last_name = forms.CharField(max_length=100, label=_('Last Name')) mfa_login_mode = forms.ChoiceField(required=False, choices=MFA_CHOICES, help_text=_("Change this to turn on " "multi-factor " "authentication (MFA).")) mobile_phone_number = USPhoneNumberField(required=False, help_text=_("US numbers only. " "We use this for " "multi-factor " "authentication.")) organization_name = forms.CharField(max_length=100, label=_('Organization Name'), required=False) create_applications = forms.BooleanField(initial=False, required=False) required_css_class = 'required' def clean_mfa_login_mode(self): mfa_login_mode = self.cleaned_data.get('mfa_login_mode') if self.request.user.is_staff and not mfa_login_mode: raise forms.ValidationError(_('MFA is not optional for staff.')) return mfa_login_mode def clean_email(self): email = self.cleaned_data.get('email') if email: if email and User.objects.filter( email=email).exclude(email=email).count(): raise forms.ValidationError(_('This email address is ' 'already registered.')) return email.rstrip().lstrip().lower() def clean_mobile_phone_number(self): mobile_phone_number = self.cleaned_data.get('mobile_phone_number', '') mfa_login_mode = self.cleaned_data.get('mfa_login_mode', '') if mfa_login_mode == "SMS" and not mobile_phone_number: raise forms.ValidationError( _('A mobile phone number is required to use SMS-based ' 'multi-factor authentication')) return mobile_phone_number def clean_username(self): username = self.cleaned_data.get('username') username = username.rstrip().lstrip().lower() if username and User.objects.filter( username=username).exclude(username=username).count(): raise forms.ValidationError(_('This username is already taken.')) return username
class ContactForm(forms.ModelForm): name = forms.CharField(max_length=150) phone = USPhoneNumberField() email = forms.CharField(max_length=150) willing_to_be_on_camera = forms.BooleanField(widget=forms.CheckboxInput, required=False) class Meta: model = Contact fields = ('name','phone','email', 'willing_to_be_on_camera')
class OrganizationForm(forms.ModelForm): phone_number = USPhoneNumberField(required=False) mailing_address_state = USStateField(widget=USStateSelect, required=True, label='State') mailing_address_zip = USZipCodeField(required=True, label='Zipcode') class Meta: model = Organization exclude = ['user', 'date_created'] def __init__(self, *args, **kwargs): super(OrganizationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'OrganizationForm' self.helper.form_class = 'form-horizontal' #self.helper.field_class = 'col-lg-4' #self.helper.label_class = 'col-lg-2' self.helper.form_tag = True self.helper.layout = Layout( Fieldset('Add Third Party Buyer', HTML(""" <p>If you are applying on behalf of an organization, family member, client or other third party who will take title, provide their name and contact information.</p> """), Field('name'), Field('email'), Field('phone_number'), css_class='well'), Fieldset('Type and Relationship', Field('entity_type'), Field('relationship_to_user'), css_class='well'), Fieldset('Mailing Address', Field('mailing_address_line1'), Field('mailing_address_line2'), Field('mailing_address_line3'), Field('mailing_address_city'), Field('mailing_address_state'), Field('mailing_address_zip'), css_class='well'), Fieldset( 'Supporting Documents', HTML(""" <p>Organizations should provide additional identifying and financial documents.</p> """), Field('sos_business_entity_report'), #Field('irs_determination_letter'), #Field('most_recent_financial_statement'), #HTML('<div class="form-group"><div class="control-label col-lg-4">Attach a file</div><div id="file-uploader" class="form-control-static col-lg-6">Drop your file here to upload</div>'), css_class='well'), FormActions( #Button('cancel', 'Cancel'), Submit('save', 'Save'))) self.helper.form_method = 'post' self.helper.form_action = ''
class AgencyForm(forms.ModelForm): """A form for an Agency""" email = FullEmailField(required=False) phone = USPhoneNumberField(required=False) fax = USPhoneNumberField(required=False) class Meta: # pylint: disable=too-few-public-methods model = Agency fields = ['name', 'aliases', 'address', 'email', 'url', 'phone', 'fax'] labels = { 'aliases': 'Alias', 'url': 'Website', 'address': 'Mailing Address' } help_texts = { 'aliases': ('An alternate name for the agency, ' 'e.g. "CIA" is an alias for "Central Intelligence Agency".') }
class ProfileForm(forms.Form): """ A form for a user to update their basic profile information """ first_name = forms.CharField(max_length=30, error_messages={'required': 'First name is required.'}) last_name = forms.CharField(max_length=30, error_messages={'required': 'Last name is required.'}) email = forms.EmailField(error_messages={'required': 'Email address is required.'}) company_name = forms.CharField(max_length=120, required=False, error_messages={}) phone = USPhoneNumberField(error_messages={'required': 'Phone number is required.'}) mobile_phone = USPhoneNumberField(required=False, error_messages={}) ship_street_1 = forms.CharField(max_length=128, required=False) ship_street_2 = forms.CharField(max_length=128, required=False) ship_city = forms.CharField(max_length=64, required=False) ship_state = forms.ChoiceField(required=False, choices=STATE_CHOICES, initial='TX') ship_postal_code = USZipCodeField(required=False) date_of_birth = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y'), input_formats=('%m/%d/%Y', '%m/%d/%y',), error_messages={'required': 'Date of Birth is required.'}) weight = forms.ChoiceField(widget=forms.Select, choices=UserProfile.WEIGHT_RANGE_CHOICES) origin_airport = AdvancedModelChoiceField(queryset=Airport.objects.all(), widget=forms.RadioSelect, required=False, empty_label=None) food_options = forms.ModelMultipleChoiceField(queryset=FoodOption.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) allergies = forms.CharField(max_length=128, required=False) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ProfileForm, self).__init__(*args, **kwargs) def clean_email(self): """ Check to see if this email already belongs to someone else. """ email = self.cleaned_data.get('email') if User.objects.filter(email=email).exclude(id=self.user.id).exists(): self._errors['email'] = self.error_class(['This email has already been used.']) return email
class SignUpPaymentAnywhereForm(forms.Form): """ Initial sign up payment form """ first_name = forms.CharField(max_length=30, error_messages={'required': 'First name is required.'}) last_name = forms.CharField(max_length=30, error_messages={'required': 'Last name is required.'}) email = forms.EmailField(error_messages={'required': 'Email address is required.'}) phone = USPhoneNumberField(error_messages={'required': 'Phone number is required.'}) token = forms.CharField(error_messages={'required': 'Payment token is required.'}) background_check = forms.BooleanField(required=False) nickname = forms.CharField(max_length=20,required=False,widget=forms.TextInput(attrs={'placeholder': 'Nickname'})) # terms = forms.BooleanField(required=True, error_messages={'required': 'Agree to the site\'s terms and conditions to continue.'}) # monarch_air_terms = forms.BooleanField(required=True, error_messages={'required': 'Agree to Monarch Air\'s terms and conditions to continue.'}) # mailchimp = forms.BooleanField(required=False, initial=True) preferred_cities = forms.ModelMultipleChoiceField(queryset=City.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) shipping_same = forms.BooleanField(required=False, initial=True) payment_method = forms.ChoiceField(choices=(('ACH', 'Bank Account'), ('Card', 'Credit Card')), widget=forms.RadioSelect) bill_street_1 = forms.CharField(max_length=128, error_messages={'required': 'Billing street address is required.'}) bill_street_2 = forms.CharField(max_length=128, required=False) bill_city = forms.CharField(max_length=64, error_messages={'required': 'Billing city is required.'}) bill_state = forms.ChoiceField(required=True, choices=STATE_CHOICES, initial='TX') bill_postal_code = USZipCodeField(error_messages={'required': 'Billing zip code is required.'}) ship_street_1 = forms.CharField(max_length=128, required=False) ship_street_2 = forms.CharField(max_length=128, required=False) ship_city = forms.CharField(max_length=64, required=False) ship_state = forms.ChoiceField(required=False, choices=STATE_CHOICES, initial='TX') ship_postal_code = USZipCodeField(required=False) def clean(self): """ If the shipping address is not the same, set fields to required and run validators again """ data = self.cleaned_data if not data.get('shipping_same'): if not data.get('ship_street_1'): self._errors['ship_street_1'] = self.error_class(['Shipping street address required.']) if not data.get('ship_city'): self._errors['ship_city'] = self.error_class(['Shipping city is required.']) if not data.get('ship_state'): self._errors['ship_state'] = self.error_class(['Shipping state is required.']) if not data.get('ship_postal_code'): self._errors['ship_postal_code'] = self.error_class(['Shipping zip code is required.']) return data
class PatientInfoForm(forms.Form): # This set of fields needs way more validation and care than I'm currently giving it # We're going to feed these results directly to the API; we should make sure the API won't choke on what we give it first_name = forms.CharField() middle_name = forms.CharField() gender = forms.ChoiceField(choices=[('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other')]) last_name = forms.CharField() date_of_birth = forms.DateField(required=False) social_security_number = USSocialSecurityNumberField(required=False) doctor = forms.ModelChoiceField(queryset=Doctor.objects.all()) address = forms.CharField(required=False) city = forms.CharField(required=False) cell_phone = USPhoneNumberField(required=False)
class AddCompanionForm(forms.Form): """ A form for adding a companion user to the current Account """ first_name = forms.CharField( max_length=30, error_messages={'required': 'First name is required.'}) last_name = forms.CharField( max_length=30, error_messages={'required': 'Last name is required.'}) email = forms.EmailField( error_messages={'required': 'Email address is required.'}) phone = USPhoneNumberField( error_messages={'required': 'Phone number is required.'}) mobile_phone = USPhoneNumberField(required=False, error_messages={}) date_of_birth = forms.DateField( widget=forms.DateInput(format='%m/%d/%Y'), input_formats=( '%m/%d/%Y', '%m/%d/%y', ), error_messages={'required': 'Date of Birth is required.'}) weight = forms.ChoiceField(widget=forms.Select, choices=UserProfile.WEIGHT_RANGE_CHOICES) def __init__(self, count, *args, **kwargs): self.account = kwargs.pop('account') super(AddCompanionForm, self).__init__(*args, **kwargs) self.count = count def clean_email(self): """ Check to see if this email already belongs to someone else. """ email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): self._errors['email'] = self.error_class( ['This email has already been used.']) return email
class SignUpForm(forms.Form): """ Form to enter initial sign-up contact information, city, and invitation code """ first_name = forms.CharField(max_length=30, error_messages={'required': 'First name is required.'}) last_name = forms.CharField(max_length=30, error_messages={'required': 'Last name is required.'}) email = forms.EmailField(error_messages={'required': 'Email address is required.'}) phone = USPhoneNumberField(error_messages={'required': 'Phone number is required.'}) origin_city = forms.ModelChoiceField(queryset=City.objects.all(), widget=forms.RadioSelect, required=False, empty_label=None) code = forms.CharField(max_length=32, required=False) other_city_checkbox = forms.BooleanField(required=False) write_in_city = forms.CharField(max_length=100, required=False) def clean(self): """ Ensure that we have either an origin_city or a write_in_city """ cleaned_data = super(SignUpForm, self).clean() origin_city = cleaned_data.get('origin_city') other_city_checkbox = cleaned_data.get('other_city_checkbox') write_in_city = cleaned_data.get('write_in_city') if other_city_checkbox and not write_in_city: self._errors['write_in_city'] = 'Please enter your own origin city' raise forms.ValidationError('Please enter your own origin city') if not origin_city and not write_in_city: raise forms.ValidationError('Please select an origin city or enter your own') return cleaned_data def clean_email(self): """ Check to see if this email is already signed up. """ email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): self._errors['email'] = self.error_class(['This email has already been used.']) return email def clean_write_in_city(self): """ Strips any whitespace off the ends of write_in_city """ write_in_city = self.cleaned_data.get('write_in_city', '') return write_in_city.strip()
class AddContactForm(forms.Form): def __init__(self, *args, **kwargs): stage_form = kwargs.pop('stage_form', False) super(AddContactForm, self).__init__(*args, **kwargs) if stage_form: self.fields['stage'].required = False, self.fields['stage'].widget = forms.HiddenInput() title = forms.CharField(max_length=20, required=False, label='Title') first_name = forms.CharField(max_length=120, label='First Name') last_name = forms.CharField(max_length=120, label='Last Name') spouse_name = forms.CharField(max_length=120, required=False, label='Spouse\'s name') phone_number = USPhoneNumberField( label="Phone Number", required=False, ) email_address = forms.EmailField(required=False, label='Email Address') street_address = forms.CharField( max_length=200, required=False, label='Street Address', ) city = forms.CharField(max_length=100, required=False, label='City') state = forms.ChoiceField(choices=STATE_CHOICES, required=False, label='State') zip = forms.RegexField( required=False, regex='^\d{5}(?:[-\s]\d{4})?$', error_messages={ 'invalid': 'Please enter a valid zip code (5 digit zip or zip+4 accepted).' }, label='ZIP Code') stage = forms.ChoiceField(choices=STAGE_OPTIONS, required=True, label='What to do next with this person:')
class SignUpForm(forms.Form): username = forms.CharField() email = forms.EmailField() phone_number = USPhoneNumberField() def __init__(self, *args, **kw): super(SignUpForm, self).__init__(*args, **kw) self.fields.keyOrder = [ 'username', 'email', 'phone_number', 'password1', 'password2', 'confirmation_key' ] def signup(self, request, user): user.phone_number = self.cleaned_data['phone_number'] user.save()
class AnywhereBasicSignUpForm(forms.Form): """ Form to enter initial sign-up contact information, city for a person invited through a Rise Anywhere flight """ first_name = forms.CharField(max_length=30, error_messages={'required': 'First name is required.'}) last_name = forms.CharField(max_length=30, error_messages={'required': 'Last name is required.'}) email = forms.EmailField(error_messages={'required': 'Email address is required.'}) phone = USPhoneNumberField(error_messages={'required': 'Phone number is required.'}) origin_city = forms.ModelChoiceField(queryset=City.objects.all(), widget=forms.RadioSelect, required=False, empty_label=None) other_city_checkbox = forms.BooleanField(required=False) write_in_city = forms.CharField(max_length=100, required=False) terms = forms.BooleanField(required=True, error_messages={'required': 'Agree to the site\'s terms and conditions to continue.'}) #removed #monarch_air_terms = forms.BooleanField(required=True, error_messages={'required': 'Agree to Monarch Air\'s terms and conditions to continue.'}) mailchimp = forms.BooleanField(required=False, initial=True) def clean(self): """ X -- Ensure that we have either an origin_city or a write_in_city Currently RiseAnywhere doesn't capture the origin city as it's not relevant """ cleaned_data = super(AnywhereBasicSignUpForm, self).clean() # origin_city = cleaned_data.get('origin_city') # other_city_checkbox = cleaned_data.get('other_city_checkbox') # write_in_city = cleaned_data.get('write_in_city') # # if other_city_checkbox and not write_in_city: # self._errors['write_in_city'] = 'Please enter your own origin city' # raise forms.ValidationError('Please enter your own origin city') # # if not origin_city and not write_in_city: # raise forms.ValidationError('Please select an origin city or enter your own') return cleaned_data def clean_email(self): """ Check to see if this email is already signed up. """ email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): self._errors['email'] = self.error_class(['This email has already been used.']) return email
class ProfileForm(forms.Form): """Define the form for the My_Info widget.""" def __init__(self, *args, **kwargs): """Override init to take a user argument.""" self.username = kwargs.pop('user', None) self.message = None super(ProfileForm, self).__init__(*args, **kwargs) display_name = forms.CharField(required=True, max_length=16, min_length=1) THEME_CHOICES = ((key, key[6:].capitalize()) for key in settings.INSTALLED_THEMES) theme = forms.ChoiceField(choices=THEME_CHOICES) # Event notifications contact_email = forms.EmailField(required=False) contact_text = USPhoneNumberField( required=False, widget=forms.TextInput(attrs={ "style": "width: 100px", })) contact_carrier = forms.ChoiceField(choices=TextReminder.TEXT_CARRIERS) def clean_display_name(self): """Check if this profile name is valid.""" name = self.cleaned_data['display_name'].strip() # Remove extra whitespace from the name. spaces = re.compile(r'\s+') name = spaces.sub(' ', name) # Check for name that is just whitespace. if name == '': raise forms.ValidationError('This field is required') # Check for duplicate name if Profile.objects.exclude(user__username=self.username).filter( name=name).count() > 0: raise forms.ValidationError( "%s is taken. Please use another name.") return name def clean_contact_email(self): """make the email lower case.""" return self.cleaned_data['contact_email'].lower()
class CallForm(forms.Form): name = forms.CharField( label=u'Имя', max_length=128, ) phone = USPhoneNumberField( label=u'Телефон', error_messages={'invalid': u'Необходимо ввести девятизначный номер.'}) def __init__(self, *args, **kwargs): super(CallForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-callForm' # self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = reverse('skv:contacts') # self.helper.form_error_title = 'Form Errors' # self.helper.form_show_errors = True self.helper.form_show_labels = False # self.helper.add_input(Submit('submit', u'Отправить')) self.helper.form_class = 'form-horizontal' # self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-12' self.helper.layout = Layout( # 'name', PrependedText(u'name', '<span class="glyphicon glyphicon-user"></span>', placeholder=u'Имя'), # 'phone', PrependedText(u'phone', '<span class="glyphicon glyphicon-phone"></span>', placeholder=u'xxx xxx-xxxx'), Div(Div(StrictButton(u'Отправить', type='submit', css_class='btn-default', name='call'), css_class="text-center"), css_class="form-group"))
class Passport(forms.Form): another_passport = forms.ChoiceField(label="Do you have a passport from another country?", choices=YES_OR_NO_RADIO, widget=UswdsRadioSelect, required=False) # @todo: Implement subsequent conditional qs. # From which country or countries do you currently have a passport? # What is the status of your current passport(s)?) travel_departure_date = forms.DateTimeField(label='Consider your upcoming travel plans. On what date (MM/DD/YYYY) do you plan to leave the United States?', help_text="If you do not have any upcoming travel plans, please leave this field blank.", required=False) travel_return_date = forms.DateTimeField(label='On what date (MM/DD/YYYY) do you plan to return?', help_text="If you do not have any upcoming travel plans, please leave this field blank.", required=False) travel_destinations = forms.CharField(label="Which country or countries will you visit?", required=False) emergency_contact_name = forms.CharField(label="Emergency contact's name", required=False) emergency_contact_phone = USPhoneNumberField(label="Emergency contact's phone number", required=False) emergency_contact_address_street = forms.CharField(label="Emergency contact's street number and name", required=False) emergency_contact_address_apt = forms.CharField(label="Emergency contact's apartment or floor number (if applicable)", required=False) emergency_contact_address_city = forms.CharField(label="Emergency contact's city", required=False) emergency_contact_address_state = forms.ChoiceField(choices=STATES, label="Emergency contact's state", required=False) # @maybe: Refactor as a USStateSelect. Also, allow non-U.S. answers. emergency_contact_address_zip = USZipCodeField(label="Emergency contact's ZIP code", required=False) # @maybe: Refactor these as CountryField()s. # Docs: https://pypi.python.org/pypi/django-countries#countryselectwidget emergency_contact_address_country = forms.CharField(label="Emergency contact's country, if outside the U.S.", required=False) emergency_contact_email = forms.EmailField(label="Emergency contact's email address", required=False) emergency_contact_relationship = forms.CharField(label="Emergency contact's relationship", required=False)
class ContactForm(forms.Form): name = forms.CharField() email_address = forms.EmailField() phone_number = USPhoneNumberField(required=False) message = forms.CharField(widget=forms.Textarea) captcha = CaptchaField() def send_mail(self, ip_address): self.cleaned_data['ip_address'] = ip_address email_message = EmailMessage() email_message.subject = 'Message from %s' % self.cleaned_data['name'] email_message.body = ''' Name: %(name)s Email address: %(email_address)s Phone number: %(phone_number)s Message: %(message)s IP address: %(ip_address)s '''.strip() % self.cleaned_data email_message.to = [settings.DEFAULT_FROM_EMAIL] email_message.send()
class CorporateSignUpConfirmForm(forms.Form): """ Form to enter initial sign-up contact information for a company account """ first_name = forms.CharField(max_length=30, error_messages={'required': 'First name is required.'}) last_name = forms.CharField(max_length=30, error_messages={'required': 'Last name is required.'}) email = forms.EmailField(error_messages={'required': 'Email address is required.'}) company = forms.CharField(max_length=30, error_messages={'required': 'Company name is required.'}) phone = USPhoneNumberField(error_messages={'required': 'Phone number is required.'}) member_count = forms.IntegerField(initial=2, error_messages={'required': 'Member count is required.'}) pass_count = forms.IntegerField(initial=2, error_messages={'required': 'Pass count is required.'}) def clean_member_count(self): count = self.cleaned_data.get('member_count') if count < 2: self.add_error('member_count', 'Corporate accounts require at least 2 members') return count def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): self.add_error('email', 'A user with that email already exists') return email def clean_pass_count(self): count = self.cleaned_data.get('pass_count') if count < 2: self.add_error('pass_count', 'Corporate accounts require at least 2 legs') if count % 2 == 1: self.add_error('pass_count', 'Legs must be in multiples of 2') return count
class VolunteerOfferForm(forms.Form): user = forms.IntegerField(required=False, widget=forms.HiddenInput) name = forms.CharField(max_length=80, label='Your Name') email = forms.EmailField(label='E-mail address') phone = USPhoneNumberField(label='Phone number') shirt_size = forms.ChoiceField(choices=([('', '')] + list(shirt_sizes)), required=False) shirt_type = forms.ChoiceField(choices=([('', '')] + list(shirt_types)), required=False) requests = forms.MultipleChoiceField( choices=(), label='Timeslots', help_text= 'Sign up for one or more shifts; remember to avoid conflicts with your classes if you\'re teaching!', widget=forms.CheckboxSelectMultiple, required=False) has_previous_requests = forms.BooleanField(widget=forms.HiddenInput, required=False, initial=False) clear_requests = forms.BooleanField(widget=forms.HiddenInput, required=False, initial=False) comments = forms.CharField( widget=forms.Textarea(attrs={ 'rows': 3, 'cols': 60 }), help_text= 'Any comments or special circumstances you would like us to know about?', required=False) confirm = forms.BooleanField( help_text= '<span style="color: red; font-weight: bold;"> I agree to show up at the time(s) selected above.</span>', required=False) def __init__(self, *args, **kwargs): if 'program' in kwargs: self.program = kwargs['program'] del kwargs['program'] else: raise KeyError( 'Need to supply program as named argument to VolunteerOfferForm' ) super(VolunteerOfferForm, self).__init__(*args, **kwargs) vrs = self.program.getVolunteerRequests() self.fields['requests'].choices = [ (v.id, '%s: %s (%d more needed)' % (v.timeslot.pretty_time(), v.timeslot.description, v.num_volunteers - v.num_offers())) for v in vrs if v.num_offers() < v.num_volunteers ] + [(v.id, '%s: %s (no more needed)' % (v.timeslot.pretty_time(), v.timeslot.description)) for v in vrs if v.num_offers() >= v.num_volunteers] # Show t-shirt fields if specified by Tag (disabled by default) if not Tag.getTag('volunteer_tshirt_options'): del self.fields['shirt_size'] del self.fields['shirt_type'] elif not Tag.getTag('volunteer_tshirt_type_selection'): del self.fields['shirt_type'] if not Tag.getTag('volunteer_allow_comments'): del self.fields['comments'] def load(self, user): self.fields['user'].initial = user.id self.fields['email'].initial = user.email self.fields['name'].initial = user.name() if user.getLastProfile().contact_user: self.fields['phone'].initial = user.getLastProfile( ).contact_user.phone_cell previous_offers = user.getVolunteerOffers(self.program).order_by('-id') if previous_offers.exists(): self.fields['has_previous_requests'].initial = True self.fields['requests'].initial = previous_offers.values_list( 'request', flat=True) if 'shirt_size' in self.fields: self.fields['shirt_size'].initial = previous_offers[ 0].shirt_size if 'shirt_type' in self.fields: self.fields['shirt_type'].initial = previous_offers[ 0].shirt_type if 'comments' in self.fields: self.fields['comments'].initial = previous_offers[0].comments def save(self): # Reset user's offers if self.cleaned_data['user']: user = ESPUser.objects.get(id=self.cleaned_data['user']) user.volunteeroffer_set.all().delete() if self.cleaned_data.get('clear_requests', False): # They want to cancel all shifts - don't do anything further. return [] # Create user if one doesn't already exist, otherwise associate a user. # Note that this will create a new user account if they enter an e-mail # address different from the one on file. if not self.cleaned_data['user']: user_data = { 'first_name': self.cleaned_data['name'].split()[0], 'last_name': ' '.join(self.cleaned_data['name'].split()[1:]), 'email': self.cleaned_data['email'], } existing_users = ESPUser.objects.filter( **user_data).order_by('-id') if existing_users.exists(): # Arbitrarily pick the most recent account # This is not too important, we just need a link to an e-mail address. user = existing_users[0] else: auto_username = ESPUser.get_unused_username( user_data['first_name'], user_data['last_name']) user = ESPUser.objects.create_user(auto_username, user_data['email']) user.__dict__.update(user_data) user.save() # Record this user account as a volunteer user.makeVolunteer() # Remove offers with the same exact contact info VolunteerOffer.objects.filter(email=self.cleaned_data['email'], phone=self.cleaned_data['phone'], name=self.cleaned_data['name']).delete() offer_list = [] for req in self.cleaned_data['requests']: o = VolunteerOffer() o.user_id = user.id o.email = self.cleaned_data['email'] o.phone = self.cleaned_data['phone'] o.name = self.cleaned_data['name'] o.confirmed = self.cleaned_data['confirm'] if 'shirt_size' in self.cleaned_data: o.shirt_size = self.cleaned_data['shirt_size'] if 'shirt_type' in self.cleaned_data: o.shirt_type = self.cleaned_data['shirt_type'] if 'comments' in self.cleaned_data: o.comments = self.cleaned_data['comments'] o.request_id = req o.save() offer_list.append(o) return offer_list def clean(self): """ Does more thorough validation since to allow flexibility, all of the form fields now have required=False. """ # If the hidden field clear_requests is True, that means the user confirmed that # they want to cancel all of their volunteer shifts; skip further validation. if not self.cleaned_data.get('clear_requests', False): # Having no shifts selected causes a different error message depending # on whether the user had existing shifts. if len(self.cleaned_data.get('requests', [])) == 0: if self.cleaned_data.get('has_previous_requests', False): raise forms.ValidationError( 'Error: You must click "Confirm" in the pop-up dialog to remove all of your previous requests.' ) else: raise forms.ValidationError( 'You did not select any volunteer shifts.') # All changes must be accompanied by the confirmation checkbox. if 'confirm' in self.cleaned_data and not self.cleaned_data[ 'confirm']: raise forms.ValidationError( 'Please confirm that you will show up to volunteer at the times you selected.' ) return self.cleaned_data