Beispiel #1
0
class ContactEditorForm(forms.ModelForm):
    phone_number = us_forms.USPhoneNumberField(required=False)
    state = us_forms.USStateField(widget=us_forms.USStateSelect,
                                  required=False)
    zip_code = us_forms.USZipCodeField(label='ZIP Code', required=False)

    class Meta:
        model = Contact
        exclude = ('user', )
Beispiel #2
0
class ZipCodeForm(forms.Form):
    """
    A zip code form.  This operates on forms that have a zip_code field.
    """
    zip_code = us_forms.USZipCodeField(required=False, label=_("Zip Code"))
    zip_range = forms.DecimalField(required=False, label=_("Range (miles)"),
                                   initial="1")

    def filter(self, qs):
        """
        Returns a new QuerySet with only items in the given zip code.
        Remember to validate this form before calling this function.
        """
        if not self.is_empty():
            zip_code = self.cleaned_data['zip_code']
            radius = self.cleaned_data['zip_range']
            zipcodeObj = ZipCode.objects.get(zipcode=zip_code)
            zipcodes = [zipcode.zipcode for zipcode in zipcodeOb.nearby(radius)]

            fvs = FieldValue.objects.filter(field__name="zip_code")
            fvs = fvs.filter(value__in=list(zipcodes))

            validAds = [fv.ad.pk for fv in fvs]

            return qs.filter(pk__in=validAds)
        else:
            return qs

    @staticmethod
    def create(fields, fieldsLeft, response=None):
        """
        Creates a new ZipCodeForm if the given fieldsLeft list contains
        'zip_code'.  Pass a dictionary (i.e. from response.GET
        or response.POST) that contains a 'zip_code' key if you want
        to initialize this form.
        """
        if 'zip_code' in fieldsLeft:
            fieldsLeft.remove('zip_code')
            if response != None:
                return ZipCodeForm({'zip_code': response['zip_code'][0],
                                    'zip_range': response['zip_range'][0]})
            else:
                return ZipCodeForm()
        else:
            return None

    def is_empty(self):
        return not ('zip_code' in self.data and \
                    self.data["zip_code"] != "" and \
                    'zip_range' in self.data and \
                    self.data["zip_range"] != "")
Beispiel #3
0
class PointImportForm(PointForm):
    __metaclass__ = ImportFormMetaClass

    zip = us_forms.USZipCodeField(required=False)
    geometry = GeometryField(geom_type='POINT', srid=4326, required=False)
    latitude = forms.FloatField(min_value=-90, max_value=90)
    longitude = forms.FloatField(min_value=-180, max_value=180)
    _cache = get_cache('geocoder')

    def clean(self):
        cleaned_data = super(PointImportForm, self).clean()
        lat, lon = cleaned_data.get('latitude'), cleaned_data.get('longitude')

        # point geometry
        geometry = cleaned_data.get('geometry')
        if not geometry:
            if not all((lat, lon)):
                raise forms.ValidationError(
                    'Geometry fields require latitude and longitude')
            geometry_field = self.fields['geometry']
            pnt = geos.Point(lon, lat, srid=geometry_field.srid)
            cleaned_data['geometry'] = geometry_field.clean(pnt)

        # zipcode geocode
        zipcode = cleaned_data.get('zip')
        if not zipcode:
            if not all((lat, lon)):
                raise forms.ValidationError(
                    'Zipcode fields require latitude and longitude')

            key = hash((lat, lon))
            result_data = self._cache.get(key)
            if result_data:
                result = GeocoderResult(result_data)
            else:
                result = Geocoder.reverse_geocode(lat=lat, lng=lon)
                self._cache.set(key, result.data)

            zipcode = result[0].postal_code
            cleaned_data['zip'] = self.fields['zip'].clean(zipcode)
        return cleaned_data
Beispiel #4
0
    def __init__(self,
                 instance,
                 show_fields=None,
                 optional_fields=None,
                 *args,
                 **kwargs):
        self.instance = instance  # an instance of UserProfile
        if show_fields is None:
            show_fields = [
                'email', 'name', 'phone_number', 'birth_date', 'image'
            ]  # 'phone_number',
        if optional_fields is None:
            optional_fields = [
                'email', 'name', 'phone_number', 'birth_date', 'image'
            ]  # 'phone_number',
        self.show_fields = show_fields
        self.optional_fields = optional_fields
        super(UserProfileForm, self).__init__(*args, **kwargs)

        email = self.instance.user.email.lower()
        is_fb_email = email.endswith('facebook.com')
        default_username = self.instance.user.username

        if is_sso_email(email) or is_fb_email:
            default_email = u''
        else:
            default_email = email

        if self.instance.is_sso:
            default_username = self.instance.sso_username

        if True:  # default_email or is_fb_email:
            self.fields['permission'] = forms.CharField(
                label=_('Who can see my profile'),
                initial=self.instance.permission,
                widget=forms.Select(choices=UserProfile.PERMISSION_CHOICES),
            )
            self.fields['send_reminders'] = forms.BooleanField(
                initial=self.instance.send_reminders,
                label=_(
                    "Email me daily reminders of upcoming events I am in for"),
                required=False)
            self.fields['send_favorites'] = forms.BooleanField(
                initial=self.instance.send_favorites,
                label=
                _("Email me daily reminders of upcoming events my friends are in for"
                  ),
                required=False)

        if 'email' in show_fields:
            self.fields['email'] = forms.EmailField(label=_('Email'),
                                                    initial=default_email,
                                                    required='email'
                                                    not in optional_fields)
            if not self.instance.is_sso and is_fb_email and (
                    self.instance.send_reminders
                    or self.instance.send_favorites):
                self.fields[
                    'email'].help_text = u'''Event reminder emails are being sent to your Facebook account.<br/> 
                                                                       Add a different email address above or leave it empty to continue 
                                                                       using your Facebook account.'''

        if 'name' in show_fields:
            self.fields['username'] = forms.RegexField(
                label=_("Username"),
                max_length=30,
                regex=r'^\w+$',
                initial=default_username,
                error_message=
                _("This value must contain only letters, numbers and underscores."
                  ),
                min_length=4,
                help_text=
                _(u'Between 4 and 30 alphanumeric characters (letters, digits and underscores).'
                  ))

            self.fields['first_name'] = forms.CharField(
                label=_('First name'),
                max_length=30,
                initial=self.instance.user.first_name,
                required='name' not in optional_fields)
            self.fields['last_name'] = forms.CharField(
                label=_('Last name'),
                max_length=30,
                initial=self.instance.user.last_name,
                required='name' not in optional_fields)

        if 'birth_date' in show_fields:
            self.fields['birth_date'] = forms.DateField(
                label=_('Date of birth'),
                input_formats=['%m/%d/%Y'],
                error_messages={
                    'invalid':
                    _('Enter a valid date in this format: MM/DD/YYYY.')
                },
                help_text=_('In the format M/D/YYYY. For example, 8/21/1985.'),
                initial=self.instance.birth_date
                and self.instance.birth_date.strftime('%m/%d/%Y') or None,
                required='birth_date' not in optional_fields)

        if 'phone_number' in show_fields:
            self.fields['phone_number'] = us_forms.USPhoneNumberField(
                label=_('Phone number'),
                initial=self.instance.phone_number,
                help_text=_('In the format: xxx-xxx-xxxx.'),
                required='phone_number' not in optional_fields)

        if 'address' in show_fields:
            try:
                adr = self.instance.address
            except Address.DoesNotExist:
                adr = Address()
            self.fields['address1'] = forms.CharField(label=_('Address 1'),
                                                      initial=adr.address1)
            self.fields['address2'] = forms.CharField(label=_('Address 2'),
                                                      required=False,
                                                      initial=adr.address2)
            self.fields['city'] = forms.CharField(label=_('City'),
                                                  max_length=100,
                                                  initial=adr.city)
            self.fields['state'] = us_forms.USStateField(
                label=_('State'),
                initial=adr.state,
                widget=us_forms.USStateSelect())
            self.fields['postal_code'] = us_forms.USZipCodeField(
                label=_('ZIP code'),
                initial=adr.postal_code,
                help_text=_(
                    'U.S. zip code in the format XXXXX or XXXXX-XXXX.'))
            #self.fields['country'] = forms.CharField(label=_('Country'), max_length=75, initial=adr.country)
            #self.fields['country'].widget.attrs.update({'class':'textInput'})

        if 'image' in show_fields:
            self.fields['image'] = forms.ImageField(label=_("Profile image"),
                                                    required=False,
                                                    help_text=AVATAR_HELP_TEXT)
        if 'name' in show_fields:
            self.fields['has_opted_in'] = forms.BooleanField(
                initial=self.instance.has_opted_in,
                label=_('Receive e-mail with news about %s.' %
                        settings.UI_SETTINGS['UI_SITE_TITLE']),
                required=False)
Beispiel #5
0
class ArtistProfileUpdateForm(ArtistPaymentSetupForm, AvatarImageCleaner):
    """Build an artist profile update form.

    Artist profile requires contact information and 
    band related information. It also requires 
    payment setup information.

    """
    # Artist/Band fields
    name = forms.CharField(label=_('Artist / Band name'), max_length=64)
    name.widget.attrs.update({'class': 'textInput'})
    # num_members = forms.IntegerField(label=_('Number of band members'), min_value=1)
    # num_members.widget.attrs.update({'class':'textInput'})
    url = forms.RegexField(
        label=_('IlliusRock URL'),
        regex=r"""^[a-zA-Z0-9\-]+$""",
        max_length=25,
        help_text=_(
            'If you enter "pink-floyd" as your url, your public homepage will be at "%spink-floyd". Only English letters, numbers, and dashes are allowed.'
            % DISPLAY_SITE_URL))
    url.widget.attrs.update({'class': 'textInput'})
    website = forms.URLField(label=_('Artist / Band website'),
                             required=False,
                             verify_exists=True,
                             max_length=150,
                             help_text=ArtistProfile.WEBSITE_HELP_TEXT)
    website.widget.attrs.update({'class': 'textInput'})
    genres = forms.MultipleChoiceField(
        label=_('Genres'),
        choices=_GENRE_CHOICES,
        help_text=_(
            'Ctrl-click or Option-click if you wish to select multiple genres.'
        ))
    genres.widget.attrs.update({'class': 'multiselectInput'})

    # Name and contact fields
    phone_number = us_forms.USPhoneNumberField(
        label=_('Phone number'), help_text=_('In the format: XXX-XXX-XXXX.'))
    phone_number.widget.attrs.update({'class': 'textInput'})
    phone_number.pre_html = _(
        'Please provide contact info for yourself or your band:')
    first_name = forms.CharField(label=_('First name'), max_length=30)
    first_name.widget.attrs.update({'class': 'textInput'})
    last_name = forms.CharField(label=_('Last name'), max_length=30)
    last_name.widget.attrs.update({'class': 'textInput'})
    address1 = forms.CharField(label=_('Address 1'), required=False)
    address1.widget.attrs.update({'class': 'textInput'})
    address2 = forms.CharField(label=_('Address 2'), required=False)
    address2.widget.attrs.update({'class': 'textInput'})
    city = forms.CharField(label=_('City'), max_length=100, required=False)
    city.widget.attrs.update({'class': 'textInput'})
    state = us_forms.USStateField(label=_('State'),
                                  widget=us_forms.USStateSelect(),
                                  required=False)
    state.widget.attrs.update({'class': 'textInput selectWider'})
    postal_code = us_forms.USZipCodeField(
        label=_('ZIP code'),
        required=False,
        help_text=_('U.S. zip code in the format XXXXX or XXXXX-XXXX.'))
    postal_code.widget.attrs.update({'class': 'textInput'})
    image = forms.ImageField(label=_("Profile image"),
                             required=False,
                             help_text=AVATAR_HELP_TEXT)
    image.widget.attrs.update({'class': 'filebrowserInput'})
    has_opted_in = forms.BooleanField(
        label=_('Receive e-mails about upcoming campaigns and news about %s.' %
                settings.UI_SETTINGS['UI_SITE_TITLE']),
        required=False)
    has_opted_in.widget.attrs.update({'class': 'checkboxInput'})

    class Media:
        _append = "?v=%s" % settings.UI_SETTINGS['UI_JS_VERSION']
        js = (settings.ADMIN_MEDIA_PREFIX + 'js/urlify.js' + _append, )

    def __init__(self, *args, **kwargs):
        user_profile_instance = kwargs.pop('user_profile_instance', None)
        self.user_profile_instance = user_profile_instance
        if not user_profile_instance:
            super(ArtistProfileUpdateForm, self).__init__(*args, **kwargs)
        else:
            # Gather initial values based on existing data.
            artist_profile = self.user_profile_instance.artist
            if artist_profile:
                if artist_profile:
                    initial_genres = [
                        g.id for g in artist_profile.genres.all()
                    ]
                else:
                    artist_profile = ArtistProfile()
                    initial_genres = []
            else:
                artist_profile = ArtistProfile()
                initial_genres = []
            try:
                adr = self.user_profile_instance.address
            except Address.DoesNotExist:
                adr = Address()
            # Populate initial values.
            initial = {}
            initial.update(self.user_profile_instance.user.__dict__)
            initial.update(self.user_profile_instance.__dict__)
            initial.update(adr.__dict__)
            initial.update(artist_profile.__dict__)
            initial['genres'] = initial_genres
            if artist_profile.paypal:
                initial.update(artist_profile.paypal.__dict__)
                initial.update(
                    {'paypal_email2': artist_profile.paypal.paypal_email})
            if artist_profile.google:
                initial.update(artist_profile.google.__dict__)
            initial.update(kwargs.pop('initial', {}))
            super(ArtistProfileUpdateForm, self).__init__(initial=initial,
                                                          *args,
                                                          **kwargs)
            if artist_profile.paypal:
                self.fields[
                    'paypal_email'].help_text = _PAYPAL_EMAIL_HELP_WITH_LINKS
            if artist_profile.google:
                self.fields['google_merchant_id'].help_text = get_gco_help()

    def clean_name(self):
        return force_unicode(strip_tags(self.cleaned_data['name']))

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

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

    def clean_url(self):
        url = self.cleaned_data['url'].lower()
        if not is_artist_url_available(
                url, getattr(self, 'user_profile_instance', None)):
            raise forms.ValidationError(
                _('That url is not available. Please try another.'))
        return url

    def save(self, profile=None, commit=True):
        if not profile:
            profile = self.user_profile_instance
        avatar_img = self.cleaned_data.get('image', None)
        if avatar_img:
            avatar_img_field = profile._meta.get_field('avatar_image')
            avatar_img_field.save_form_data(profile, avatar_img)
        artist_profile = self.save_artist_profile(profile, commit=commit)
        ArtistPaymentSetupForm.save(self,
                                    artist_profile=artist_profile,
                                    commit=commit)
        if avatar_img:
            profile._create_resized_images(raw_field=None, save=commit)
        return artist_profile

    def save_artist_profile(self, profile, commit=True):
        """`profile` is an instance of UserProfile"""
        user = profile.user
        profile.is_artist = True
        profile.phone_number = self.cleaned_data['phone_number']
        if 'has_opted_in' in self.fields:
            profile.has_opted_in = self.cleaned_data.get('has_opted_in', False)
        if commit:
            profile.save()
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        if commit:
            user.save()
        adr1 = self.cleaned_data.get('address1', '')
        city = self.cleaned_data.get('city', '')
        state = self.cleaned_data.get('state', '')
        postal_code = self.cleaned_data.get('postal_code', '')
        if adr1 and city and state and postal_code:
            adr = Address(user_profile=profile)
            adr.address1 = adr1
            adr.address2 = self.cleaned_data.get('address2', '')
            adr.city = city
            adr.state = state
            adr.postal_code = postal_code
            if commit:
                adr.save()
        artist_profile = ArtistProfile(user_profile=profile)
        artist_profile.name = self.cleaned_data['name']
        artist_profile.num_members = self.cleaned_data.get('num_members', 2)
        artist_profile.url = self.cleaned_data['url']
        artist_profile.website = self.cleaned_data.get('website', None)
        if commit:
            artist_profile.save()
            artist_profile.genres = list(
                Genre.objects.filter(id__in=self.cleaned_data['genres']))
        return artist_profile
Beispiel #6
0
class PropertyForm(forms.ModelForm):
    state = us_forms.USStateField(widget=us_forms.USStateSelect)
    zip = us_forms.USZipCodeField(widget=forms.TextInput(attrs={'size': 10}))

    class Meta:
        model = models.Property