Beispiel #1
0
class LocationSetupForm(ModelForm):
    class Meta:
        model = LocationSetup
    zip=USZipCodeField()
    state=forms.TypedChoiceField(choices=US_STATES, initial="DC")
    ward=forms.TypedChoiceField(choices=WARD_CHOICES)
    required_css_class = 'required'
Beispiel #2
0
def PostalCodeField(*args, **kwargs):
    if settings.POSTAL_CODE_FIELD == "GBPostcodeField":
        from django.contrib.localflavor.uk.forms import UKPostcodeField
        return UKPostcodeField(*args, **kwargs)
    else:
        from django.contrib.localflavor.us.forms import USZipCodeField
        return USZipCodeField(*args, **kwargs)
class ActorSignupForm(ModelForm):
  """A form that allows an actor to signup"""
  line1 = forms.CharField(max_length = 128, label=_('Address line 1'), 
    widget=forms.TextInput(attrs={'size': '40'})
  )
  line2 = forms.CharField(max_length = 128, label=_('Address line 2'), 
    required=False,
    widget=forms.TextInput(attrs={'size': '40'})
  )
  city = forms.CharField(max_length = 128, label=_('City'))
  state = USStateSelect()
  zipcode = USZipCodeField()
  phone = USPhoneNumberField(label=_('Phone (xxx-xxx-xxxx)'))

  
  
  class Meta:
    model = Actor

  def __init__(self, *args, **kwargs):
    super(ActorSignupForm, self).__init__(*args, **kwargs)
    
    self.fields['size'].label = _('Suit/Dress size')
    self.fields['union'].label = _('Union or Non-Union? (SAG, AFTRA, etc.)')
    self.fields['special'].label = _('Special Abilities')
    self.fields['reference'].label = _('How did you hear about us? (Include talent agency if applicable)')
Beispiel #4
0
class CityStateZipCode(forms.Form):
    """
    And sometimes we need the City and State with the zipcode
    """
    city = forms.CharField(max_length=255)
    state = USStateField(widget=USStateSelect)
    zipcode = USZipCodeField()
Beispiel #5
0
class UserProfileEditForm(forms.ModelForm):
    zipcode = USZipCodeField()
    phone = USPhoneNumberField()
    
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'address_line_1', 'address_line_2', 'city', 'state', 'zipcode', 'phone']
Beispiel #6
0
    class _ProfileForm(forms.ModelForm):
        email = forms.EmailField(widget=forms.TextInput(),
                                 label="Email address",
                                 required=False)
        zip_code = USZipCodeField(required=False)

        class Meta:
            model = profile_mod
            # planning to remove volunteer attr..
            exclude = (
                'user',
                'volunteer',
            )  # User will be filled in by the view.

        def clean_email(self):
            """
            Validate that the supplied email address is unique for the
            site.
            
            """
            if User.objects.filter(email__iexact=self.cleaned_data['email']):
                raise forms.ValidationError(
                    _("This email address is already in use. Please supply a different email address."
                      ))
            return self.cleaned_data['email']
Beispiel #7
0
class SubmitEstablishmentForm(forms.ModelForm):
    zip_code = USZipCodeField()
    
    class Meta:
        model = Establishment
        fields = ('name', 'establishment_type', 'access', 
                  'street_address', 'city', 'zip_code',
                  'phone', 'link')
Beispiel #8
0
class AddressForm(forms.Form):
    """
    Address form for new signup
    """
    address1 = forms.CharField(max_length=255)
    address2 = forms.CharField(max_length=255, required=False)
    city = forms.CharField(max_length=255)
    state = USStateField(widget=USStateSelect)
    zipcode = USZipCodeField()
Beispiel #9
0
class BaseProfileForm(forms.Form):
    phone = USPhoneNumberField(required=False)
    city = forms.CharField()
    state = USStateField(
        widget=USStateSelect,
        help_text="Please select the state you will volunteer in.")
    zipcode = USZipCodeField(required=True, label="ZIP code")
    is_a = forms.ChoiceField(required=False,
                             choices=IS_A_CHOICES,
                             label='I am a:')
Beispiel #10
0
class UserProfileForm(ModelForm):
    home_address_zip = USZipCodeField()

    class Meta:
        model = UserProfile
        fields = ('home_address_street', 'home_address_city',
                  'home_address_state', 'home_address_zip',
                  'home_phone_number', 'mobile_phone_number',
                  'drivers_license_number', 'drivers_license_state',
                  'drivers_license_class', 'drivers_license_expiration')
Beispiel #11
0
class ProfileFormUS(ProfileForm):
    phone_number = USPhoneNumberField(required=False)
    zipcode = USZipCodeField(required=False)

    def __init__(self, *args, **kwargs):
        super(ProfileFormUS, self).__init__(*args, **kwargs)
        self.fields['state'] = forms.ModelChoiceField(
            queryset=states_in_the_US(),
            help_text=
            'Please use "Other" listed at the end for a non-US address')
Beispiel #12
0
class USPostalAddressForm(PostalAddressForm):
    line1 = forms.CharField(label=_(u"Street"), max_length=50)
    line2 = forms.CharField(label=_(u"Area"), required=False, max_length=100)
    city = forms.CharField(label=_(u"City"), max_length=50)
    state = USStateField(label=_(u"US State"), widget=USStateSelect)
    code = USZipCodeField(label=_(u"Zip Code"))

    def __init__(self, *args, **kwargs):
        super(USPostalAddressForm, self).__init__(*args, **kwargs)
        self.fields['country'].initial = "US"
Beispiel #13
0
class UserProfileBaseForm(forms.Form):
    sex = forms.ChoiceField(choices=sex_choices, required=False)
    country = forms.ChoiceField(choices=country_choices, required=False)
    city = forms.CharField(max_length=64, required=False)
    state = USStateField(required=False)
    zip_code = USZipCodeField(required=False)
    income = forms.ChoiceField(choices=income_choices, required=False)
    ethnicity = forms.ChoiceField(choices=ethnicity_choices, required=False)
    sexual_orientation = forms.ChoiceField(choices=interested_in_choices, required=False)
    relationship_status = forms.ChoiceField(choices=relationship_status_choices, required=False)
    political = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}),max_length=30, required=False)
    religious = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}),max_length=30, required=False)
    education = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}), max_length=64, required=False)
    work = forms.CharField(widget=forms.TextInput(attrs={ 'autocomplete':'off'}), max_length=64, required=False)
Beispiel #14
0
class PaymentForm(forms.Form):
    """
    Credit card form
    """

    # This field is used internally whan the form is split.
    ready           = forms.BooleanField(  required = False,
                                           initial = False,
                                           widget = forms.HiddenInput()
                                        )
    

    number          = CreditCardField()
    
    expire_month    = forms.ChoiceField( choices = MONTH_CHOICES,
                                         widget = forms.Select(attrs={'class':"selectbox1"})
                                       )
    
    expire_year     = forms.ChoiceField( choices = [],
                                         widget = forms.Select(attrs={'class':"selectbox1"})
                                       )
    
    
    address         = forms.CharField   ( max_length = 100,
                                          widget = forms.TextInput(attrs={'id':"inputext1"})
                                        )
    
    address2         = forms.CharField  ( required = False,
                                          max_length = 100,
                                          widget = forms.TextInput(attrs={'id':"inputext1"})
                                        )
    
    city            = forms.CharField   ( max_length = 100,
                                          widget = forms.TextInput(attrs={'id':"inputext1"})
                                        )
    
    state           = forms.CharField   ( max_length = 2,
                                          widget = forms.TextInput(attrs={'class':"stateabbr"})  
                                        )

    zipcode         = USZipCodeField    ( required = False,
                                          widget= forms.TextInput(attrs={'class':"eightythree"})
                                        )
    
    def __init__(self,*args, **kwargs):
        super(PaymentForm, self).__init__(*args, **kwargs)
        self.fields['expire_year'].choices =  [(yr,yr) for yr in xrange(date.today().year,date.today().year + 8)]
Beispiel #15
0
class TreeRegistrationForm(RegistrationForm):
    volunteer = forms.BooleanField(required=False)
    updates = forms.BooleanField(required=False)
    first_name = forms.RegexField(
        regex=r'^\w',
        max_length=30,
        widget=forms.TextInput(),
        label=_("First Name"),
        error_messages={'invalid': _("This value must contain only letters")},
        required=False)
    last_name = forms.RegexField(
        regex=r'^\w',
        max_length=30,
        widget=forms.TextInput(),
        label=_("Last Name"),
        error_messages={'invalid': _("This value must contain only letters")},
        required=False)
    zip_code = USZipCodeField(required=False)
    photo = forms.ImageField(required=False)
Beispiel #16
0
class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(label=u'Password', widget=forms.PasswordInput(render_value=False))
    retyped_password = forms.CharField(label=u'Retype Password', widget=forms.PasswordInput(render_value=False))
    zipcode = USZipCodeField()
    phone = USPhoneNumberField()

    def __init__(self, *args, **kwargs):
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = [
            'username',
            'first_name',
            'last_name',
            'email',
            'password',
            'retyped_password',
            'address_line_1',
            'address_line_2',
            'city',
            'state',
            'zipcode',
            'phone']
    
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'password', 'address_line_1', 'address_line_2', 'city', 'state', 'zipcode', 'phone']

    def clean(self):
        cleaned_data = self.cleaned_data
        password = cleaned_data.get('password', '')
        retyped_password = cleaned_data.get('retyped_password', '')
        
        if password != retyped_password:
            raise ValidationError('Password and retyped password didn\'t match.')
        
        return cleaned_data

    def save(self, force_insert=False, force_update=False, commit=True, *args, **kwargs):
        user = super(UserRegistrationForm, self).save(*args, **kwargs)
        password = user.password
        user.set_password(password)
        user.save()
        
        return user
Beispiel #17
0
class CFCSignupForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(CFCSignupForm, self).__init__(*args, **kwargs)
        self.fields['state']._fill_choices(states_in_the_US())
        self.fields['actioncenter']._fill_choices(vibha_action_centers())

    first_name = forms.CharField(label="First Name", max_length=100)
    last_name = forms.CharField(label="Last Name", max_length=100)
    pg_first_name = forms.CharField(label="Parent/Guardian First Name",
                                    max_length=100,
                                    required=False)
    pg_last_name = forms.CharField(label="Parent/Guardian Last Name",
                                   max_length=100,
                                   required=False)
    email = forms.EmailField(label="E-mail")
    phone = USPhoneNumberField()
    address_1 = forms.CharField(label="Address Line1",
                                max_length=100,
                                required=False)
    address_2 = forms.CharField(label="Address Line2",
                                max_length=100,
                                required=False)
    city = forms.CharField(label="City", max_length=100, required=False)
    state = vibhaforms.ForeignKeyChoiceField(required=False)
    actioncenter = vibhaforms.ForeignKeyChoiceField(required=False)
    zipcode = USZipCodeField(required=False)
    comments = forms.CharField(label="Comments",
                               widget=forms.Textarea(),
                               required=False)
    receipt = forms.BooleanField(
        label="Need receipt?",
        required=False,
        help_text="""If the donation box is kept at a common
                     place like office cubicle or break room where anybody
                     can drop the change, that money is not tax
                     deductible""")
    agreement = forms.BooleanField(
        label="Agreement",
        help_text="""By selecting this option, I attest that I
                     am above 18 years of age or my parent/guardian has
                     approved signing up for this program""")
class ShopInfoForm(forms.Form):
    name_store = forms.RegexField(
        max_length=60,
        label=_("Your shop's name"),
        regex=r'^[\s\w+-]+$',
        error_messages={
            'invalid':
            _("This value may contain only letters, numbers and - character.")
        })
    shop_name = forms.CharField(max_length=60,
                                label=_("Your shop's web address"),
                                help_text=".greatcoins.com")
    first_name = forms.CharField(max_length=50, label=_("Your First Name"))
    last_name = forms.CharField(max_length=50, label=_("Your Last Name"))
    street = forms.CharField(max_length=100)
    city = forms.CharField(max_length=100)
    state = forms.CharField(widget=USStateSelect)
    zip = USZipCodeField()
    promotional_code = forms.CharField(max_length=100, required=False)

    def clean_shop_name(self):
        shop_name = self.cleaned_data["shop_name"]
        try:
            Shop.objects.get(name=shop_name)
        except Shop.DoesNotExist:
            return shop_name
        raise forms.ValidationError(_("A shop with that name already exists."))

    def clean(self):
        cleaned_data = self.cleaned_data
        try:
            user = self.initial['user']
            first_name = cleaned_data.get('first_name', None)
            last_name = cleaned_data.get('last_name', None)
            user.first_name = first_name
            user.last_name = last_name
            user.save()
        except:
            pass
        return cleaned_data
Beispiel #19
0
class VenueForm(BootstrapForm):
    class Meta:
        layout = (Fieldset(
            "Update a venue",
            "name",
            "street",
            "city",
            "state",
            "zip",
            "latitude",
            "longitude",
            "valid_dates",
        ), )

    name = forms.CharField(max_length=75)
    street = forms.CharField(max_length=75)
    city = forms.CharField(max_length=25)
    state = USStateField()
    zip = USZipCodeField()
    latitude = forms.DecimalField()
    longitude = forms.DecimalField()
    valid_dates = forms.CharField(widget=CalendarWidget)
Beispiel #20
0
class ArtistForm(ModelForm):
    zipcode = USZipCodeField()

    class Meta:
        model = Artist
        exclude = ('user', 'slug', 'startswith')
Beispiel #21
0
class ZipCodeForm(forms.Form):
    """
    Sometimes we just need the zipcode
    """
    zipcode = USZipCodeField()
Beispiel #22
0
class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)
    zipcode = USZipCodeField()
Beispiel #23
0
class ZipCodeForm(forms.Form):
    zipcode = USZipCodeField()
class ShopBillingForm(forms.Form):

    #Billing Address
    shop_address = forms.BooleanField(required=False,
                                      initial=False,
                                      label=_("Use shop address"))

    billing_street = forms.CharField(max_length=100, required=False)
    billing_city = forms.CharField(max_length=100, required=False)
    billing_state = forms.CharField(widget=USStateSelect, required=False)
    billing_zip = USZipCodeField(required=False)

    #Billing information
    cc_number = forms.CharField(max_length=60,
                                label=_("Credit Card Number"),
                                initial=INITIAL_CC)
    cc_expiration_month = forms.ChoiceField(choices=MONTHS)
    cc_expiration_year = forms.ChoiceField(choices=YEARS)
    card_security_number = forms.CharField(max_length=4,
                                           label=_("Card Security Number"),
                                           required=True)

    terms = forms.BooleanField(required=False)

    def clean_terms(self):
        terms = self.cleaned_data["terms"]
        if terms:
            return terms
        else:
            raise forms.ValidationError(
                _("You must agree to the terms and conditions before you can create your account."
                  ))

    def clean(self):
        init_user = self.initial['user']
        cleaned_data = self.cleaned_data

        #        try:
        #            a = self.initial.get("result")
        #            logging.critical(a)
        #            return cleaned_data
        #        except Exception:
        #            pass
        #
        #        logging.critical("Trying to validate credit cards")

        if cleaned_data.has_key('cc_expiration_year') and cleaned_data.has_key(
                'cc_expiration_month'):
            date_str = "%s-%s" % (cleaned_data['cc_expiration_year'],
                                  cleaned_data['cc_expiration_month'])
            card_expire = datetime.datetime.strptime(date_str, "%Y-%m")

            if card_expire < datetime.datetime.now():
                msg = u"Card expired."
                self._errors["cc_expiration_year"] = self.error_class([msg])
                self._errors["cc_expiration_month"] = self.error_class([msg])

                # These fields are no longer valid. Remove them from the
                # cleaned data.
                del cleaned_data["cc_expiration_year"]
                del cleaned_data["cc_expiration_month"]

        bt_gw = BraintreeGateway(settings.MERCHANT_ID, settings.PUBLIC_KEY,
                                 settings.PRIVATE_KEY)

        first_name = init_user.first_name
        last_name = init_user.first_name

        email = init_user.email
        cc_number = cleaned_data.get("cc_number", None)
        if cc_number is None:
            self._errors["cc_number"] = self.error_class(
                ["This field is required!"])

        month = cleaned_data.get("cc_expiration_month", None)
        year = cleaned_data.get("cc_expiration_year", None)

        if month is None or year is None:
            raise forms.ValidationError(_("Expiration date invalid format."))

        cc_expiration_date = "%s/%s" % (month, year)
        cc_security_number = cleaned_data.get("card_security_number", None)
        if cc_security_number is None:
            self._errors["card_security_number"] = self.error_class(
                ["This field is required!"])

        reuse_address = cleaned_data.get("shop_address", None)

        if reuse_address == False:
            #Take data filled by user in the form
            street = cleaned_data.get("billing_street", None)
            if street is None or street == u'':
                self._errors["billing_street"] = self.error_class(
                    ["This field is required!"])
            city = cleaned_data.get("billing_city", None)
            if city is None or city == u'':
                self._errors["billing_city"] = self.error_class(
                    ["This field is required!"])
            state = cleaned_data.get("billing_state", None)
            if state is None or state == u'':
                self._errors["billing_state"] = self.error_class(
                    ["This field is required!"])
            zip = cleaned_data.get("billing_zip", None)
            if zip is None or zip == u'':
                self._errors["billing_zip"] = self.error_class(
                    ["This field is required!"])
        else:
            #Use data filled on first step
            street = self.initial['street']
            zip = self.initial['zip']
            state = self.initial['state']
            city = self.initial['city']

        shop_name = "thisisafake.shop.com"
        shop_id = "-1"

        result = bt_gw.create_customer(first_name, last_name, email, cc_number,
                                       cc_expiration_date, cc_security_number,
                                       street, city, state, zip, shop_name,
                                       shop_id)
        if result.is_success:
            self.result = result
            self.initial["result"] = result
        else:
            raise forms.ValidationError(_(result.message))

        return cleaned_data
Beispiel #25
0
class TreeAddForm(forms.Form):
    edit_address_street = forms.CharField(
        max_length=200,
        required=True,
        initial="Enter an Address or Intersection")
    geocode_address = forms.CharField(widget=forms.HiddenInput,
                                      max_length=255,
                                      required=True)
    edit_address_city = forms.CharField(max_length=200,
                                        required=False,
                                        initial="Enter a City")
    edit_address_zip = USZipCodeField(widget=forms.HiddenInput, required=False)
    lat = forms.FloatField(widget=forms.HiddenInput, required=True)
    lon = forms.FloatField(widget=forms.HiddenInput, required=True)
    initial_map_location = forms.CharField(max_length=200,
                                           required=False,
                                           widget=forms.HiddenInput)
    species_name = forms.CharField(required=False,
                                   initial="Enter a Species Name")
    species_other1 = forms.CharField(required=False, initial="Genus")
    species_other2 = forms.CharField(required=False, initial="species")
    species_id = forms.CharField(widget=forms.HiddenInput, required=False)
    dbh = forms.FloatField(required=False, label="Trunk size")
    dbh_type = forms.ChoiceField(required=False,
                                 widget=forms.RadioSelect,
                                 choices=[('diameter', 'Diameter'),
                                          ('circumference', 'Circumference')])
    height = forms.FloatField(required=False, label="Tree height")
    canopy_height = forms.IntegerField(required=False)
    plot_width = forms.ChoiceField(required=False,
                                   choices=[('1', '1'), ('2', '2'), ('3', '3'),
                                            ('4', '4'), ('5', '5'), ('6', '6'),
                                            ('7', '7'), ('8', '8'), ('9', '9'),
                                            ('10', '10'), ('11', '11'),
                                            ('12', '12'), ('13', '13'),
                                            ('14', '14'), ('15', '15'),
                                            ('99', '15+')])
    plot_length = forms.ChoiceField(required=False,
                                    choices=[('1', '1'), ('2', '2'), ('3',
                                                                      '3'),
                                             ('4', '4'), ('5', '5'),
                                             ('6', '6'), ('7', '7'),
                                             ('8', '8'), ('9', '9'),
                                             ('10', '10'), ('11', '11'),
                                             ('12', '12'), ('13', '13'),
                                             ('14', '14'), ('15', '15'),
                                             ('99', '15+')])
    plot_width_in = forms.ChoiceField(required=False,
                                      choices=[('1', '1'), ('2', '2'),
                                               ('3', '3'), ('4', '4'),
                                               ('5', '5'), ('6', '6'),
                                               ('7', '7'), ('8', '8'),
                                               ('9', '9'), ('10', '10'),
                                               ('11', '11')])
    plot_length_in = forms.ChoiceField(required=False,
                                       choices=[('1', '1'), ('2', '2'),
                                                ('3', '3'), ('4', '4'),
                                                ('5', '5'), ('6', '6'),
                                                ('7', '7'), ('8', '8'),
                                                ('9', '9'), ('10', '10'),
                                                ('11', '11')])
    plot_type = forms.TypedChoiceField(
        choices=Choices().get_field_choices('plot_type'), required=False)
    power_lines = forms.TypedChoiceField(
        choices=Choices().get_field_choices('powerline_conflict_potential'),
        required=False)
    sidewalk_damage = forms.ChoiceField(
        choices=Choices().get_field_choices('sidewalk_damage'), required=False)
    condition = forms.ChoiceField(
        choices=Choices().get_field_choices('condition'), required=False)
    canopy_condition = forms.ChoiceField(
        choices=Choices().get_field_choices('canopy_condition'),
        required=False)
    target = forms.ChoiceField(
        required=False,
        choices=[('addsame',
                  'I want to add another tree using the same tree details'),
                 ('add', 'I want to add another tree with new details'),
                 ('edit', 'I\'m done!')],
        initial='edit',
        widget=forms.RadioSelect)
    owner_additional_id = forms.CharField(required=False)

    def __init__(self, *args, **kwargs):
        super(TreeAddForm, self).__init__(*args, **kwargs)
        if not self.fields['plot_type'].choices[0][0] == '':
            self.fields['plot_type'].choices.insert(0, ('', 'Select One...'))
            self.fields['power_lines'].choices.insert(0, ('', 'Select One...'))
            self.fields['sidewalk_damage'].choices.insert(
                0, ('', 'Select One...'))
            self.fields['condition'].choices.insert(0, ('', 'Select One...'))
            self.fields['canopy_condition'].choices.insert(
                0, ('', 'Select One...'))
            self.fields['plot_width'].choices.insert(0, ('', 'Select Feet...'))
            self.fields['plot_width_in'].choices.insert(
                0, ('', 'Select Inches...'))
            self.fields['plot_length'].choices.insert(0,
                                                      ('', 'Select Feet...'))
            self.fields['plot_length_in'].choices.insert(
                0, ('', 'Select Inches...'))

    def clean(self):
        cleaned_data = self.cleaned_data
        height = cleaned_data.get('height')
        canopy_height = cleaned_data.get('canopy_height')
        try:
            point = Point(cleaned_data.get('lon'),
                          cleaned_data.get('lat'),
                          srid=4326)
            nbhood = Neighborhood.objects.filter(geometry__contains=point)
        except:
            raise forms.ValidationError(
                "This tree is missing a location. Enter an address in Step 1 and update the map to add a location for this tree."
            )

        if nbhood.count() < 1:
            raise forms.ValidationError(
                "The selected location is outside our area. Please specify a location within the "
                + settings.REGION_NAME + " region.")

        if height > 300:
            raise forms.ValidationError("Height is too large.")
        if canopy_height > 300:
            raise forms.ValidationError("Canopy height is too large.")

        if canopy_height and height and canopy_height > height:
            raise forms.ValidationError(
                "Canopy height cannot be larger than tree height.")

        # initial_map_location is an optional field so only trigger the validation if it was specified
        if cleaned_data.get('initial_map_location'):
            initial_map_location = cleaned_data.get(
                'initial_map_location').split(',')
            initial_point = Point(float(initial_map_location[1]),
                                  float(initial_map_location[0]),
                                  srid=4326)
            if point == initial_point:
                raise forms.ValidationError(
                    "We need a more precise location for the tree. Please move the tree marker from the default location for this address to the specific location of the tree planting site. "
                )

        return cleaned_data

    def save(self, request):
        from django.contrib.gis.geos import Point

        plot = Plot()
        plot.data_owner = request.user

        address = self.cleaned_data.get('edit_address_street')
        if address:
            plot.address_street = address
            plot.geocoded_address = address
        city = self.cleaned_data.get('edit_address_city')
        geo_address = self.cleaned_data.get('geocode_address')
        if geo_address:
            plot.geocoded_address = geo_address
        if city:
            plot.address_city = city
        zip_ = self.cleaned_data.get('edit_address_zip')
        if zip_:
            plot.address_zip = zip_

        plot_width = self.cleaned_data.get('plot_width')
        plot_width_in = self.cleaned_data.get('plot_width_in')
        if plot_width:
            plot.width = float(plot_width)
        if plot_width_in:
            plot.width = plot.width + (float(plot_width_in) / 12)
        plot_length = self.cleaned_data.get('plot_length')
        plot_length_in = self.cleaned_data.get('plot_length_in')
        if plot_length:
            plot.length = float(plot_length)
        if plot_length_in:
            plot.length = plot.length + (float(plot_length_in) / 12)
        plot_type = self.cleaned_data.get('plot_type')
        if plot_type:
            plot.type = plot_type
        power_lines = self.cleaned_data.get('power_lines')
        if power_lines != "":
            plot.powerline_conflict_potential = power_lines
        sidewalk_damage = self.cleaned_data.get('sidewalk_damage')
        if sidewalk_damage:
            plot.sidewalk_damage = sidewalk_damage
        owner_additional_id = self.cleaned_data.get('owner_additional_id')
        if owner_additional_id:
            plot.owner_additional_id = owner_additional_id

        import_event, created = ImportEvent.objects.get_or_create(
            file_name='site_add', )
        plot.import_event = import_event

        pnt = Point(self.cleaned_data.get('lon'),
                    self.cleaned_data.get('lat'),
                    srid=4326)
        plot.geometry = pnt
        plot.last_updated_by = request.user
        plot.save()

        species = self.cleaned_data.get('species_id')
        species_other1 = self.cleaned_data.get('species_other1')
        species_other2 = self.cleaned_data.get('species_other2')
        height = self.cleaned_data.get('height')
        canopy_height = self.cleaned_data.get('canopy_height')
        dbh = self.cleaned_data.get('dbh')
        dbh_type = self.cleaned_data.get('dbh_type')
        condition = self.cleaned_data.get('condition')
        canopy_condition = self.cleaned_data.get('canopy_condition')

        #TODO: fix this
        if species or height or canopy_height or dbh or condition or canopy_condition:
            # print species, height, canopy_height, dbh, condition, canopy_condition
            if species:
                spp = Species.objects.filter(id=species)
                if spp:
                    new_tree = Tree(species=spp[0])
                else:
                    new_tree = Tree()
            else:
                new_tree = Tree()

            if species_other1:
                new_tree.species_other1 = species_other1
            if species_other2:
                new_tree.species_other2 = species_other2
            if height:
                new_tree.height = height
            if canopy_height:
                new_tree.canopy_height = canopy_height
            if dbh:
                if dbh_type == 'circumference':
                    new_tree.dbh = dbh / math.pi
                else:
                    new_tree.dbh = dbh
            if condition:
                new_tree.condition = condition
            if canopy_condition:
                new_tree.canopy_condition = canopy_condition

            new_tree.import_event = import_event
            new_tree.last_updated_by = request.user
            new_tree.plot = plot
            new_tree.save()
            #print new_tree.__dict__

        return plot
Beispiel #26
0
 def __init__(self, *args, **kwargs):
     if not event.changed_version:
         changed_version = EventChange(event=event)
     else:
         changed_version = event.changed_version
     kwargs['instance'] = changed_version
     initial = {}
     # Set initial values from changed version or from event
     for fname in EventChange.MERGE_FIELDS:
         value = getattr(changed_version, fname) or getattr(
             event, fname)
         if isinstance(value, models.Model):
             value = value.pk
         initial[fname] = value
     for fname in EventChange.BOOLEAN_MERGE_FIELDS:
         changed = getattr(changed_version, fname)
         orig = getattr(event, fname)
         initial[fname] = (changed_version.pk and [changed]
                           or [orig])[0]
     kwargs['initial'] = initial
     super(EventChangeForm, self).__init__(*args, **kwargs)
     self.fields['title'] = forms.RegexField(
         label=_("Title"),
         max_length=255,
         regex=r"""^[a-zA-Z0-9 '.",!?:;\-\(\)]+$""",
         help_text=Event.TITLE_HELP,
         required=False,
         error_message=
         _("The title must consist of English letters, numbers, and punctuation only."
           ))
     self.fields['title'].widget.attrs.update({'class': 'textInput'})
     self.fields['max_attendees'].min_value = 0
     self.fields['max_attendees'].widget.attrs.update(
         {'class': 'textInput'})
     self.fields['price'].min_value = 0
     self.fields['price'].error_messages.update(
         {'invalid': 'Enter a number (without the dollar sign.)'})
     self.fields['price'].widget.attrs.update({'class': 'textInput'})
     self.fields['description'].widget.attrs.update({
         'class': 'textareaInput htmlEdit',
         'rows': 20
     })
     self.fields['venue'].widget.attrs.update({'class': 'textInput'})
     self.fields['zip_code'] = USZipCodeField(
         label=_("Zip Code"),
         help_text=Event.ZIPCODE_HELP,
         required=False)
     self.fields['zip_code'].widget.attrs.update({'class': 'textInput'})
     self.fields['event_date'].widget.attrs.update(
         {'class': 'textInput dateInput vDateField'})
     self.fields['event_start_time'].widget.attrs.update(
         {'class': 'textInput timeInput vTimeField'})
     # self.fields['event_end_time'].widget.attrs.update({'class':'textInput timeInput vTimeField'})
     self.fields['event_timezone'].widget.attrs.update(
         {'class': 'textInput'})
     self.fields['min_age'].required = False
     self.fields['min_age'].min_value = 0
     self.fields['min_age'].max_value = settings.EVENT_MIN_AGE_RANGE[1]
     self.fields['min_age'].widget.attrs.update({'class': 'textInput'})
     self.fields['audio_player_embed'].widget.attrs.update(
         {'class': 'textareaInput'})
     self.fields['mp3_url'].widget.attrs.update({'class': 'textInput'})
     self.fields['embed_service'].widget.attrs.update(
         {'class': 'dropdownList'})
     self.fields['embed_url'].widget.attrs.update(
         {'class': 'textInput'})
     # Disallow editing of inapplicable fields
     if event.is_sold_out or event.is_complete:
         # Don't allow attendee related changes
         del self.fields['max_attendees']
         del self.fields['price']
     # Remove date fields if dates have passed
     now = date.today()
     if event.event_date < now:
         del self.fields['event_date']
         del self.fields['event_start_time']
Beispiel #27
0
class AuthNetForm(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()
    address = forms.CharField()
    city = forms.CharField()
    state = forms.CharField(widget=USStateSelect)
    zip = USZipCodeField()
    card_num = forms.RegexField(
        label='Credit card number',
        regex=r'[\d -]+',
        error_messages={'invalid': 'Please enter a valid credit card number.'})
    month = forms.CharField()
    year = forms.CharField()
    card_code = forms.IntegerField(label='CCV')

    def __init__(self, data=None, order=None, *args, **kwargs):
        self.order = order
        order_settings = self.order.site.ordersettings
        self.login = order_settings.auth_net_api_login
        self.key = order_settings.auth_net_api_key
        initial = {
            'month': 'MM',
            'year': 'YYYY',
        }
        try:
            initial['first_name'], initial[
                'last_name'] = self.order.name.split(' ')
        except ValueError:
            pass
        initial['address'] = self.order.street
        for attr in ('city', 'state', 'zip'):
            initial[attr] = getattr(self.order, attr, '')
        super(AuthNetForm, self).__init__(data,
                                          initial=initial,
                                          *args,
                                          **kwargs)

    def clean_card_num(self):
        card_num = self.cleaned_data['card_num']
        card_num = re.sub(r' |-', '', card_num)
        return card_num

    def clean_month(self):
        month = self.cleaned_data['month']
        msg = 'Please enter a valid month (00-12).'
        try:
            month = int(month)
        except ValueError:
            raise forms.ValidationError(msg)
        if 0 <= month <= 12:
            return month
        raise forms.ValidationError(msg)

    def clean_year(self):
        year = self.cleaned_data['year']
        current_year = date.today().year
        msg = 'Please enter a valid year (%d or later).' % current_year
        try:
            year = int(year)
        except ValueError:
            raise forms.ValidationError(msg)
        if year < current_year:
            raise forms.ValidationError(msg)
        return year

    def clean(self):
        cleaned_data = self.cleaned_data
        if self._errors:
            return cleaned_data
        data = cleaned_data.copy()
        api = Api(self.login, self.key, delimiter=u'|')
        exp_date = '-'.join([str(data.pop('month')), str(data.pop('year'))])
        transaction = api.transaction(type=u'AUTH_CAPTURE',
                                      amount=self.order.total_plus_tax(),
                                      invoice_num=unicode(self.order.id),
                                      description=u'Order for %s' %
                                      self.order.name,
                                      exp_date=unicode(exp_date),
                                      **data)
        if transaction['reason_code'] != u'1':
            msg = 'We were unable to process your transaction. Please verify that your payment information is correct.'
            raise forms.ValidationError(msg)
        return cleaned_data
Beispiel #28
0
class NonUserProfileForm(forms.ModelForm):
    class Meta:
        model = NonUserProfile

    zipcode = USZipCodeField()
Beispiel #29
0
class TreeAddForm(forms.Form):
    edit_address_street = forms.CharField(max_length=200, required=True, initial="Enter an Address or Intersection")
    geocode_address = forms.CharField(widget=forms.HiddenInput, max_length=255, required=True)
    edit_address_city = forms.CharField(max_length=100, required=False, initial="Enter a City")
    edit_latitude = forms.CharField(max_length=100, required=False, initial="Latitude")
    edit_longitude = forms.CharField(max_length=100, required=False, initial="Longitude")
    edit_address_zip = USZipCodeField(widget=forms.HiddenInput, required=False)
    lat = forms.FloatField(widget=forms.HiddenInput,required=True)
    lon = forms.FloatField(widget=forms.HiddenInput,required=True)
    species_name = forms.CharField(required=False, initial="Enter a Species Name")
    species_id = forms.CharField(widget=forms.HiddenInput, required=False)
    dbh = forms.FloatField(required=False, label="Trunk size")
    crown_width = forms.FloatField(required=False, label="Crown Diameter")
    dbh_type = forms.ChoiceField(required=False, widget=forms.RadioSelect, choices=[('diameter', 'Diameter'), ('circumference', 'Circumference')])
    height = forms.FloatField(required=False, label="Tree height")
    canopy_height = forms.IntegerField(required=False)
    plot_width = forms.ChoiceField(required=False, label="Enter the planting site length", choices=[('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6','6'),('7','7'),('8','8'),('9','9'),('10','10'),('11','11'),('12','12'),('13','13'),('14','14'),('15','15'),('99','15+')])
    plot_length = forms.ChoiceField(required=False, label="Enter the planting site width", choices=[('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6','6'),('7','7'),('8','8'),('9','9'),('10','10'),('11','11'),('12','12'),('13','13'),('14','14'),('15','15'),('99','15+')])
    plot_width_in = forms.ChoiceField(required=False, choices=[('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6','6'),('7','7'),('8','8'),('9','9'),('10','10'),('11','11')])
    plot_length_in = forms.ChoiceField(required=False, choices=[('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6','6'),('7','7'),('8','8'),('9','9'),('10','10'),('11','11')])
    plot_type = forms.TypedChoiceField(choices=Choices().get_field_choices('plot_type'), required=False)
    power_lines = forms.TypedChoiceField(choices=Choices().get_field_choices('powerline_conflict_potential'), required=False)
    sidewalk_damage = forms.ChoiceField(choices=Choices().get_field_choices('sidewalk_damage'), required=False)
    condition = forms.ChoiceField(choices=Choices().get_field_choices('condition'), required=False)
    canopy_condition = forms.ChoiceField(choices=Choices().get_field_choices('canopy_condition'), required=False)
    fauna = forms.MultipleChoiceField(choices=Choices().get_field_choices('fauna'), required=False, widget=forms.CheckboxSelectMultiple)
    target = forms.ChoiceField(required=False, choices=[('add', 'I want to add another tree'), ('edit', 'I\'m done!')], initial='edit', widget=forms.RadioSelect)        

    def __init__(self, *args, **kwargs):
        super(TreeAddForm, self).__init__(*args, **kwargs)
        if not self.fields['plot_type'].choices[0][0] == '':        
            self.fields['plot_type'].choices.insert(0, ('','Select One...' ) )
            self.fields['power_lines'].choices.insert(0, ('','Select One...' ) )
            self.fields['sidewalk_damage'].choices.insert(0, ('','Select One...' ) )
            self.fields['condition'].choices.insert(0, ('','Select One...' ) )
            self.fields['canopy_condition'].choices.insert(0, ('','Select One...' ) )
            self.fields['plot_width'].choices.insert(0, ('','Select Feet...' ) )
            self.fields['plot_width_in'].choices.insert(0, ('','Select Inches...' ) )
            self.fields['plot_length'].choices.insert(0, ('','Select Feet...' ) )
            self.fields['plot_length_in'].choices.insert(0, ('','Select Inches...' ) )


    def clean(self):        
        cleaned_data = self.cleaned_data 
        height = cleaned_data.get('height')
        canopy_height = cleaned_data.get('canopy_height') 
        try:
            point = Point(cleaned_data.get('lon'),cleaned_data.get('lat'),srid=4326)  
            nbhood = Neighborhood.objects.filter(geometry__contains=point)
        except:
            raise forms.ValidationError("This tree is missing a location. Enter an address in Step 1 and update the map to add a location for this tree.") 
        
        if nbhood.count() < 1:
            raise forms.ValidationError("The selected location is outside our area. Please specify a location within the " + settings.REGION_NAME + " region.")
        
        if height > 300:
            raise forms.ValidationError("Height is too large.")
        if canopy_height > 300:
            raise forms.ValidationError("Canopy height is too large.")

        if canopy_height and height and canopy_height > height:
            raise forms.ValidationError("Canopy height cannot be larger than tree height.")
            

        return cleaned_data 
        
    def save(self,request):
        from django.contrib.gis.geos import Point

        plot = Plot()
        plot.data_owner = request.user

        address = self.cleaned_data.get('edit_address_street')
        if address:
            plot.address_street = address
            plot.geocoded_address = address
        city = self.cleaned_data.get('edit_address_city')
        geo_address = self.cleaned_data.get('geocode_address')
        if geo_address:
            plot.geocoded_address = geo_address
        if city:
            plot.address_city = city
        zip_ = self.cleaned_data.get('edit_address_zip')
        if zip_:
            plot.address_zip = zip_
        
        plot_width = self.cleaned_data.get('plot_width')
        plot_width_in = self.cleaned_data.get('plot_width_in')
        if plot_width:
            plot.width = float(plot_width)
        if plot_width_in:
            plot.width = plot.width + (float(plot_width_in) / 12)
        plot_length = self.cleaned_data.get('plot_length')
        plot_length_in = self.cleaned_data.get('plot_length_in')
        if plot_length:
            plot.length = float(plot_length)
        if plot_length_in:
            plot.length = plot.length + (float(plot_length_in) / 12)
        plot_type = self.cleaned_data.get('plot_type')
        if plot_type:
            plot.type = plot_type
        power_lines = self.cleaned_data.get('power_lines')
        if power_lines != "":
            plot.powerline_conflict_potential = power_lines
        sidewalk_damage = self.cleaned_data.get('sidewalk_damage')
        if sidewalk_damage:
            plot.sidewalk_damage = sidewalk_damage

        import_event, created = ImportEvent.objects.get_or_create(file_name='site_add',)
        plot.import_event = import_event

        pnt = Point(self.cleaned_data.get('lon'),self.cleaned_data.get('lat'),srid=4326)
        plot.geometry = pnt
        plot.last_updated_by = request.user
        plot.save()

        species = self.cleaned_data.get('species_id')
        height = self.cleaned_data.get('height')
        canopy_height = self.cleaned_data.get('canopy_height')
        dbh = self.cleaned_data.get('dbh')
        crown_width = self.cleaned_data.get('crown_width')
        dbh_type = self.cleaned_data.get('dbh_type')
        condition = self.cleaned_data.get('condition')
        canopy_condition = self.cleaned_data.get('canopy_condition')

        new_tree = Tree()
        if species:
            spp = Species.objects.filter(symbol=species)
            if spp:
              new_tree.species=spp[0]

        if crown_width:
            new_tree.crown_width = crown_width
        if height:
            new_tree.height = height
        if canopy_height:
            new_tree.canopy_height = canopy_height
        if dbh:
            if dbh_type == 'circumference':
                dbh = dbh / math.pi
            new_tree.dbh = dbh
        if condition:
            new_tree.condition = condition
        if canopy_condition:
            new_tree.canopy_condition = canopy_condition
        
        new_tree.import_event = import_event            
        new_tree.last_updated_by = request.user
        new_tree.plot = plot
        new_tree.save()
        #print new_tree.__dict__
        fauna = self.cleaned_data.get('fauna')
        if fauna:
            print 'fauna',fauna
            fauna_dict = dict(Choices().get_field_choices('fauna'))
            for f in fauna:
              fauna = TreeFauna()
              fauna.reported_by = request.user
              fauna.key = f
              fauna.value = datetime.now()
              fauna.fauna = fauna_dict[f] # or random string
              fauna.tree = new_tree
              fauna.save()
        
        return plot
Beispiel #30
0
 def get_address_zip_field(self):
     return USZipCodeField(label=_("Zipcode"))