class InquiryForm(forms.ModelForm): class Meta: model = Applicant fields = ('fname', 'lname', 'mname', 'sex', 'bday', 'street', 'city', 'state', 'zip', 'parent_email', 'family_preferred_language', 'siblings', 'year', 'ethnicity', 'hs_grad_yr', 'hs_grad_yr', 'religion', 'country_of_birth', 'heard_about_us', 'present_school_typed', 'present_school_type_typed') ethnicity_other = forms.CharField(required=False) language_other = forms.CharField(required=False) religion_other = forms.CharField(required=False) # Parent p_lname = forms.CharField(required=False) p_fname = forms.CharField(required=False) p_relationship_to_child = forms.ChoiceField(required=False, choices=(('Mother','Mother'),('Father','Father'),('Guardian','Guardian'))) p_address = forms.CharField(required=False) p_city = forms.CharField(required=False) p_state = us_forms.USStateField(required=False, widget=forms.Select(choices=STATE_CHOICES)) p_zip = forms.CharField(required=False) p_home = us_forms.USPhoneNumberField(required=False) p_work = us_forms.USPhoneNumberField(required=False) p_work_ext = forms.CharField(required=False, widget=forms.TextInput(attrs={'style':'width:3em;'})) p_mobile = us_forms.USPhoneNumberField(required=False) p_email = forms.EmailField(required=False) spam_regex = re.compile(r'^[5\-]+$') spam = forms.CharField(required=True, validators=[RegexValidator(regex=spam_regex)])
class VehicleEnquiryForm(forms.Form): # always have the same field names stock_number, vin, year_mfd, make, model # look at inventory.models.Vehicle.handlebars_context for explanation stock_number = forms.CharField(max_length=20, widget=forms.HiddenInput()) vin = forms.CharField(max_length=20, widget=forms.HiddenInput()) year_mfd = forms.IntegerField(widget=forms.HiddenInput()) make = forms.ModelChoiceField(queryset=VehicleMake.objects.all(), widget=forms.HiddenInput()) model = forms.ModelChoiceField(queryset=VehicleModel.objects.all(), widget=forms.HiddenInput()) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) email = forms.EmailField(required=False) address = forms.CharField(required=False) city = forms.CharField(max_length=100) state = us_forms.USStateField(widget=us_forms.USStateSelect) zip_code = us_forms.USZipCodeField() phone = us_forms.USPhoneNumberField(required=False) message = forms.CharField(widget=forms.TextInput()) def clean(self): cleaned_data = super(VehicleEnquiryForm, self).clean() email = cleaned_data.get('email') phone = cleaned_data.get('phone') if len(email) == 0 and len(phone) == 0: # At least one of them has to be provided msg = "At least one of email or phone have to be provided" self.add_error('email', msg) self.add_error('phone', msg)
class ShippingAddressForm(checkout_forms.ShippingAddressForm): state = us_forms.USStateField(label="State", widget=us_forms.USStateSelect) def __init__(self, *args, **kwargs): super(ShippingAddressForm, self).__init__(*args, **kwargs) self.fields['postcode'].label = _("Zip code") self.fields['state'].help_text = _( "Only orders going to New Jersey are liable for Sales tax")
class ShippingAddressForm(checkout_forms.ShippingAddressForm): state = us_forms.USStateField( widget=floppyforms.Select(choices=STATE_CHOICES_WITH_EMPTY), required=False) def __init__(self, *args, **kwargs): super(ShippingAddressForm, self).__init__(*args, **kwargs) self.fields['country'].empty_label = ""
class EventForm(forms.Form): title = forms.CharField(label="Title", required=False) date = forms.DateField(label="Date", required=False) time = forms.TimeField(label="Time", required=False) venue = forms.CharField(label="Venue", required=True) address = forms.CharField(label="Address", required=True) city = forms.CharField(label="City", required=True) state = usforms.USStateField(label="State", required=True) zip = usforms.USZipCodeField(label="ZIP", required=True) max_attendees = forms.IntegerField(label="Max Attendees", required=True) host = forms.EmailField(label="Host's Email Address", required=True) public_description = forms.CharField(label="Description", required=False, widget=forms.Textarea()) directions = forms.CharField(label="Directions", required=False, widget=forms.Textarea()) def clean_host(self): host = self.cleaned_data['host'] try: user = CoreUser.objects.using("ak").get(email=host) except CoreUser.DoesNotExist: raise forms.ValidationError("No core_user exists with email %s" % host) return user def clean(self): try: data = self.build_event_struct() except: pass else: self.event_struct = data return self.cleaned_data def build_event_struct(self): data = {} for key in "title venue city state zip max_attendees".split(): data[key] = self.cleaned_data.get(key) for key in "directions public_description".split(): if key in self.cleaned_data and self.cleaned_data.get(key).strip(): data[key] = self.cleaned_data.get(key) data['creator_id'] = self.cleaned_data['host'].id data['address1'] = self.cleaned_data['address'] data['starts_at'] = datetime.combine(self.cleaned_data['date'], self.cleaned_data['time']) return data
class Search(forms.Form): first_name = forms.CharField( label='First name', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'First Name'})) last_name = forms.CharField( label='Last name', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Last Name'})) high_school = forms.CharField( required=False, label='High School', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'High School'})) university = forms.CharField( required=False, label='University', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'University'})) hometown = forms.CharField( required=False, label='Hometown', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Hometown'})) current_city = forms.CharField( required=False, label='Current City', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Current City'})) state = lfforms.USStateField( required=False, widget=forms.TextInput(attrs={'placeholder': 'State'})) employer = forms.CharField( required=False, label='Employer', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Employer'})) orgs = forms.CharField( required=False, label='Other Organization', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Other Organizations'})) username = forms.CharField( required=False, label='Any Username', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Any Username'}))
class ContactForm(forms.Form): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) email = forms.EmailField(required=False) address = forms.CharField(required=False) city = forms.CharField(max_length=100) state = us_forms.USStateField(widget=us_forms.USStateSelect) zip_code = us_forms.USZipCodeField() phone = us_forms.USPhoneNumberField(required=False) message = forms.CharField(widget=forms.TextInput()) def clean(self): cleaned_data = super(ContactForm, self).clean() email = cleaned_data.get('email') phone = cleaned_data.get('phone') if len(email) == 0 and len(phone) == 0: # At least one of them has to be provided msg = "At least one of email or phone have to be provided" self.add_error('email', msg) self.add_error('phone', msg)
class ApartmentUploadForm(forms.Form): city = forms.CharField(label="City", max_length=100) state = us_forms.USStateField(label="State") address = forms.CharField(label="Address", max_length=255) zipcode = us_forms.USZipCodeField(label="Zip Code") rent_price = forms.DecimalField( label="Rent Price ($)", max_digits=20, decimal_places=2, validators=[MinValueValidator(1), MaxValueValidator(100000)], ) number_of_bed = forms.IntegerField( label="Bedrooms", validators=[MinValueValidator(0), MaxValueValidator(10)]) # Handling input files with Django # https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html image = forms.ImageField() suite_num = forms.CharField(label="Suite Number", max_length=30) description = forms.CharField(widget=forms.Textarea) def clean_suite_num(self): """checks for apartments with duplicate suite numbers in the same location""" city = self.cleaned_data.get("city") state = self.cleaned_data.get("state") address = self.cleaned_data.get("address") zipcode = self.cleaned_data.get("zipcode") suite_num = self.cleaned_data.get("suite_num") if suite_num.strip()[0] == "-": raise forms.ValidationError( "You cannot submit an apartment with a negative Suite Number") try: # If the apartment belongs to a location that already exists loc = Location.objects.get(city=city, state=state, address=address, zipcode=zipcode) try: Apartment.objects.get(suite_num=suite_num, location=loc) raise forms.ValidationError( "An apartment with the same suite number already exists at this location! \ If you are the landlord, you can edit the apartment details by going to your account page." ) except Apartment.DoesNotExist: return suite_num except Location.DoesNotExist: # if the apartment belongs to a location that does not exist, we can't have duplicate apartments return suite_num def clean(self): super(ApartmentUploadForm, self).clean() address = self.cleaned_data.get("address") city = self.cleaned_data.get("city") state = self.cleaned_data.get("state") zipcode = self.cleaned_data.get("zipcode") g_data = fetch_geocode(f"{address}, {city} {state}, {zipcode}") if len(g_data) == 0: raise forms.ValidationError( "Unable to locate that address, please check that it was entered correctly." ) g_address = g_utils.get_address(g_data) g_city = g_utils.get_city(g_data)[0] g_state = g_utils.get_state(g_data) g_zip = g_utils.get_zipcode(g_data) if g_city != city: self.add_error( "city", f"The input value of {city} did not match the resolved value of {g_city}", ) if g_state != state: self.add_error( "state", f"The input value of {state} did not match the resolved value of {g_state}", ) if g_zip != zipcode: self.add_error( "zipcode", f"The input value of {zipcode} did not match the resolved value of {g_zip}", ) if g_address[0].lower() not in address.lower(): self.add_error( "address", f"The input value of {address} did not contain the resolved value {g_address[0]}", ) if g_address[1].lower() not in address.lower(): self.add_error( "address", f"The input value of {address} did not contain the resolved value {g_address[1]}", )
class BillingAddressForm(payment_forms.BillingAddressForm): """ Extended version of the core billing address form that adds a field so customers can choose to re-use their shipping address. """ SAME_AS_SHIPPING, NEW_ADDRESS = 'same-address', 'different-address' CHOICES = ( (SAME_AS_SHIPPING, 'Use shipping address'), (NEW_ADDRESS, 'Enter a new address'), ) billing_option = forms.ChoiceField( widget=forms.RadioSelect, choices=CHOICES, initial=SAME_AS_SHIPPING) state = us_forms.USStateField(widget=floppyforms.Select(choices=STATE_CHOICES_WITH_EMPTY), required=False) class Meta(payment_forms.BillingAddressForm): model = UserAddress exclude = ('search_text', 'user', 'num_orders', 'hash', 'is_default_for_billing', 'is_default_for_shipping') def __init__(self, shipping_address, user, data=None, *args, **kwargs): # Store a reference to the shipping address self.shipping_address = shipping_address super(BillingAddressForm, self).__init__(data, *args, **kwargs) self.instance.user = user # If no shipping address (eg a download), then force the # 'same_as_shipping' field to have a certain value. if shipping_address is None: self.fields['billing_option'].choices = ( (self.NEW_ADDRESS, 'Enter a new address'),) self.fields['billing_option'].initial = self.NEW_ADDRESS # If using same address as shipping, we don't need require any of the # required billing address fields. if data and data.get('billing_option', None) == self.SAME_AS_SHIPPING: for field in self.fields: if field != 'billing_option': self.fields[field].required = False def _post_clean(self): # Don't run model validation if using shipping address if self.cleaned_data.get('billing_option') == self.SAME_AS_SHIPPING: return super(BillingAddressForm, self)._post_clean() def save(self, commit=True): if self.cleaned_data.get('billing_option') == self.SAME_AS_SHIPPING: # Convert shipping address into billing address billing_addr = BillingAddress() self.shipping_address.populate_alternative_model(billing_addr) if commit: billing_addr.save() return billing_addr else: address = super(BillingAddressForm, self).save(commit=False) try: address = UserAddress.objects.get( user=self.instance.user, hash=address.generate_hash()) last_address = UserAddress.objects.get(user=self.instance.user, is_default_for_billing=True) last_address.is_default_for_billing = False address.is_default_for_billing = True address.save() except UserAddress.DoesNotExist: address.is_default_for_billing = True address.save() return address def validate_unique(self): pass
class ShippingAddressForm(forms.ShippingAddressForm): postcode = us_forms.USZipCodeField(label="Zip code") state = us_forms.USStateField(label="State", widget=us_forms.USStateSelect)
class ShippingAddressForm(checkout_forms.ShippingAddressForm): state = us_forms.USStateField(label="State", widget=us_forms.USStateSelect) def __init__(self, *args, **kwargs): super(ShippingAddressForm, self).__init__(*args, **kwargs) self.fields['postcode'].label = _("Zip code")