Ejemplo n.º 1
0
class SubmitContactForm(forms.Form):

    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100, required=False)

    address = forms.CharField(max_length=50, required=False)
    city = forms.CharField(max_length=50, required=False)
    state = forms.CharField(max_length=50, required=False)
    zipcode = forms.CharField(max_length=10, required=False)
    country = CountrySelectField(required=False)

    phone = forms.CharField(max_length=20, required=False)
    email = EmailVerificationField(label=_("Email"))
    url = forms.URLField(label=_('URL'), max_length=200, required=False)

    message = forms.CharField(widget=forms.Textarea)
    captcha = CaptchaField(label=_('Type the code below'))
Ejemplo n.º 2
0
class DirectoryForm(TendenciBaseForm):
    body = forms.CharField(required=False,
                           widget=TinyMCE(
                               attrs={'style': 'width:100%'},
                               mce_attrs={
                                   'storme_app_label':
                                   Directory._meta.app_label,
                                   'storme_model':
                                   Directory._meta.module_name.lower()
                               }))

    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))

    list_type = forms.ChoiceField(initial='regular',
                                  choices=(
                                      ('regular', 'Regular'),
                                      ('premium', 'Premium'),
                                  ))
    payment_method = forms.CharField(
        error_messages={'required': 'Please select a payment method.'})
    remove_photo = forms.BooleanField(label=_('Remove the current logo'),
                                      required=False)

    activation_dt = SplitDateTimeField(initial=datetime.now())
    expiration_dt = SplitDateTimeField(initial=datetime.now())

    email = EmailVerificationField(label=_("Email"), required=False)
    email2 = EmailVerificationField(label=_("Email 2"), required=False)

    pricing = forms.ModelChoiceField(label=_('Requested Duration'),
                                     queryset=DirectoryPricing.objects.filter(
                                         status=True).order_by('duration'))

    class Meta:
        model = Directory
        fields = (
            'headline',
            'slug',
            'summary',
            'body',
            'logo',
            'source',
            'timezone',
            'first_name',
            'last_name',
            'address',
            'address2',
            'city',
            'state',
            'zip_code',
            'country',
            'phone',
            'phone2',
            'fax',
            'email',
            'email2',
            'website',
            'tags',
            'pricing',
            'list_type',
            'payment_method',
            'activation_dt',
            'expiration_dt',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_user_edit',
            'syndicate',
            'user_perms',
            'member_perms',
            'group_perms',
            'status',
            'status_detail',
        )

        fieldsets = [('Directory Information', {
            'fields': [
                'headline',
                'slug',
                'summary',
                'body',
                'logo',
                'tags',
                'source',
                'timezone',
                'activation_dt',
                'pricing',
                'expiration_dt',
            ],
            'legend':
            ''
        }),
                     ('Payment', {
                         'fields': ['list_type', 'payment_method'],
                         'classes': ['payment_method'],
                     }),
                     ('Contact', {
                         'fields': [
                             'first_name', 'last_name', 'address', 'address2',
                             'city', 'state', 'zip_code', 'country', 'phone',
                             'phone2', 'fax', 'email', 'email2', 'website'
                         ],
                         'classes': ['contact'],
                     }),
                     ('Permissions', {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     ('Administrator Only', {
                         'fields': ['syndicate', 'status', 'status_detail'],
                         'classes': ['admin-only'],
                     })]

    def clean_logo(self):
        logo = self.cleaned_data['logo']
        if logo:
            extension = splitext(logo.name)[1]

            # check the extension
            if extension.lower() not in ALLOWED_LOGO_EXT:
                raise forms.ValidationError(
                    'The logo must be of jpg, gif, or png image type.')

            # check the image header
            image_type = '.%s' % imghdr.what('', logo.read())
            if image_type not in ALLOWED_LOGO_EXT:
                raise forms.ValidationError(
                    'The logo is an invalid image. Try uploading another logo.'
                )

            max_upload_size = get_max_file_upload_size()
            if logo.size > max_upload_size:
                raise forms.ValidationError(
                    _('Please keep filesize under %s. Current filesize %s') %
                    (filesizeformat(max_upload_size), filesizeformat(
                        logo.size)))

        return logo

    def __init__(self, *args, **kwargs):
        super(DirectoryForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['body'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
            if self.user.profile.is_superuser:
                self.fields['status_detail'].choices = (
                    ('active', 'Active'),
                    ('inactive', 'Inactive'),
                    ('pending', 'Pending'),
                    ('paid - pending approval', 'Paid - Pending Approval'),
                )
        else:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = 0

        if self.instance.logo:
            self.fields[
                'logo'].help_text = '<input name="remove_photo" id="id_remove_photo" type="checkbox"/> Remove current logo: <a target="_blank" href="/site_media/media/%s">%s</a>' % (
                    self.instance.logo, basename(self.instance.logo.file.name))
        else:
            self.fields.pop('remove_photo')

        if not self.user.profile.is_superuser:
            if 'status' in self.fields: self.fields.pop('status')
            if 'status_detail' in self.fields: self.fields.pop('status_detail')

        if self.fields.has_key('payment_method'):
            self.fields['payment_method'].widget = forms.RadioSelect(
                choices=get_payment_method_choices(self.user))
        if self.fields.has_key('pricing'):
            self.fields['pricing'].choices = get_duration_choices(self.user)

        # expiration_dt = activation_dt + requested_duration
        fields_to_pop = ['expiration_dt']
        if not self.user.profile.is_superuser:
            fields_to_pop += [
                'slug', 'entity', 'allow_anonymous_view', 'user_perms',
                'member_perms', 'group_perms', 'post_dt', 'activation_dt',
                'syndicate', 'status', 'status_detail'
            ]

        for f in list(set(fields_to_pop)):
            if f in self.fields:
                self.fields.pop(f)

    def save(self, *args, **kwargs):
        directory = super(DirectoryForm, self).save(*args, **kwargs)
        if self.cleaned_data.has_key('pricing'):
            directory.requested_duration = self.cleaned_data[
                'pricing'].duration
        if self.cleaned_data.get('remove_photo'):
            directory.logo = None
        return directory
Ejemplo n.º 3
0
class JobForm(TendenciBaseForm):

    description = forms.CharField(
        required=False,
        widget=TinyMCE(
            attrs={'style': 'width:100%'},
            mce_attrs={'storme_app_label': Job._meta.app_label, 'storme_model': Job._meta.module_name.lower()}
        )
    )

    captcha = CaptchaField()

    start_dt = SplitDateTimeField(
        required=False,
        label=_('Position starts on:'),
        initial=datetime.now())

    activation_dt = SplitDateTimeField(
        label=_('Activation Date/Time'),
        initial=datetime.now())

    post_dt = SplitDateTimeField(
        label=_('Post Date/Time'),
        initial=datetime.now())

    expiration_dt = SplitDateTimeField(
        label=_('Expiration Date/Time'),
        initial=datetime.now())

    status_detail = forms.ChoiceField(
        choices=(('active', 'Active'), ('inactive', 'Inactive'), ('pending', 'Pending'),))

    list_type = forms.ChoiceField(initial='regular', choices=(('regular', 'Regular'),
                                                              ('premium', 'Premium'),))
    payment_method = forms.CharField(error_messages={'required': 'Please select a payment method.'})

    contact_email = EmailVerificationField(label=_("Contact email"), required=False)

    group = forms.ModelChoiceField(queryset=Group.objects.filter(status=True, status_detail="active"), required=True, empty_label=None)

    pricing = forms.ModelChoiceField(queryset=JobPricing.objects.filter(status=True).order_by('duration'),
                **request_duration_defaults)

    class Meta:
        model = Job
        fields = (
            'title',
            'slug',
            'description',
            'group',
            'code',
            'location',
            'skills',
            'experience',
            'education',
            'level',
            'period',
            'is_agency',
            'contact_method',
            'position_reports_to',
            'salary_from',
            'salary_to',
            'computer_skills',
            'tags',
            'pricing',
            'list_type',
            'start_dt',
            'activation_dt',
            'post_dt',
            'expiration_dt',
            'job_url',
            'entity',
            'contact_company',
            'contact_name',
            'contact_address',
            'contact_address2',
            'contact_city',
            'contact_state',
            'contact_zip_code',
            'contact_country',
            'contact_phone',
            'contact_fax',
            'contact_email',
            'contact_website',
            'tags',
            'allow_anonymous_view',
            'syndicate',
            'status',
            'status_detail',
            'payment_method',
        )

        fieldsets = [
            ('Job Information', {
                'fields': [
                    'title',
                    'slug',
                    'description',
                    'group',
                    'job_url',
                    'start_dt',
                    'code',
                    'location',
                    'skills',
                    'computer_skills',
                    'experience',
                    'education',
                    'level',
                    'period',
                    'contact_method',
                    'position_reports_to',
                    'salary_from',
                    'salary_to',
                    'is_agency',
                    'tags',
                    'pricing',
                    'activation_dt',
                    'expiration_dt',
                    'post_dt',
                    'entity'
                ],
                'legend': ''
            }),
            ('Payment', {
                'fields': ['list_type',
                           'payment_method'],
                'classes': ['payment_method'],
            }),
            ('Contact', {
                'fields': [
                    'contact_company',
                    'contact_name',
                    'contact_address',
                    'contact_address2',
                    'contact_city',
                    'contact_state',
                    'contact_zip_code',
                    'contact_country',
                    'contact_phone',
                    'contact_fax',
                    'contact_email',
                    'contact_website'
                ],
                'classes': ['contact'],
            }),
            ('Security Code', {
                'fields': ['captcha'],
                'classes': ['captcha'],
            }),
            ('Permissions', {
                'fields': [
                    'allow_anonymous_view',
                    'user_perms',
                    'member_perms',
                    'group_perms',
                ],
                'classes': ['permissions'],
            }),
            ('Administrator Only', {
                'fields': ['syndicate',
                           'status',
                           'status_detail'],
                'classes': ['admin-only'],
            })]

    def __init__(self, *args, **kwargs):
        if hasattr(self, 'user'):
            kwargs.update({'user': self.user})
        super(JobForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['description'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            #self.fields['pricing'].initial = JobPricing.objects.filter(duration=self.instance.requested_duration)[0]
            if self.user.profile.is_superuser:
                self.fields['status_detail'].choices = STATUS_DETAIL_CHOICES
        else:
            self.fields['description'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['group'].initial = Group.objects.get_initial_group_id()

        self.fields['pricing'].choices = pricing_choices(self.user)

        if 'payment_method' in self.fields:
            self.fields['payment_method'].widget = forms.RadioSelect(choices=get_payment_method_choices(self.user))

        # adjust fields depending on user status
        fields_to_pop = []
        if not self.user.is_authenticated():
            fields_to_pop += [
                'entity',
                'allow_anonymous_view',
                'user_perms',
                'group_perms',
                'member_perms',
                'post_dt',
                'activation_dt',
                'expiration_dt',
                'syndicate',
                'status',
                'status_detail'
            ]
        else:
            fields_to_pop += [
                'captcha'
            ]

        if not self.user.profile.is_superuser:
            fields_to_pop += [
                'slug',
                'entity',
                'group',
                'allow_anonymous_view',
                'user_perms',
                'member_perms',
                'group_perms',
                'post_dt',
                'activation_dt',
                'expiration_dt',
                'syndicate',
                'status',
                'status_detail'
            ]

        for f in list(set(fields_to_pop)):
            if f in self.fields:
                self.fields.pop(f)

    def save(self, *args, **kwargs):
        """
        Assigns the requested_duration of a job based on the
        chosen pricing.
        """
        job = super(JobForm, self).save(commit=False)
        if 'pricing' in self.cleaned_data:
            job.requested_duration = self.cleaned_data['pricing'].duration
        if kwargs['commit']:
            job.save()
        return job
Ejemplo n.º 4
0
class ProfileForm(TendenciBaseForm):

    first_name = forms.CharField(
        label=_("First Name"),
        max_length=100,
        error_messages={'required': 'First Name is a required field.'})
    last_name = forms.CharField(
        label=_("Last Name"),
        max_length=100,
        error_messages={'required': 'Last Name is a required field.'})
    email = EmailVerificationField(
        label=_("Email"),
        error_messages={'required': 'Email is a required field.'})
    email2 = EmailVerificationField(label=_("Secondary Email"), required=False)

    initials = forms.CharField(label=_("Initial"),
                               max_length=100,
                               required=False,
                               widget=forms.TextInput(attrs={'size': '10'}))
    display_name = forms.CharField(
        label=_("Display name"),
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={'size': '30'}))

    url = forms.CharField(label=_("Web Site"),
                          max_length=100,
                          required=False,
                          widget=forms.TextInput(attrs={'size': '40'}))
    company = forms.CharField(
        label=_("Company"),
        max_length=100,
        required=False,
        error_messages={'required': 'Company is a required field.'},
        widget=forms.TextInput(attrs={'size': '45'}))
    department = forms.CharField(label=_("Department"),
                                 max_length=100,
                                 required=False,
                                 widget=forms.TextInput(attrs={'size': '35'}))
    address = forms.CharField(
        label=_("Address"),
        max_length=150,
        required=False,
        error_messages={'required': 'Address is a required field.'},
        widget=forms.TextInput(attrs={'size': '45'}))
    address2 = forms.CharField(label=_("Address2"),
                               max_length=100,
                               required=False,
                               widget=forms.TextInput(attrs={'size': '40'}))
    city = forms.CharField(
        label=_("City"),
        max_length=50,
        required=False,
        error_messages={'required': 'City is a required field.'},
        widget=forms.TextInput(attrs={'size': '15'}))
    state = forms.CharField(
        label=_("State"),
        max_length=50,
        required=False,
        error_messages={'required': 'State is a required field.'},
        widget=forms.TextInput(attrs={'size': '5'}))
    zipcode = forms.CharField(
        label=_("Zipcode"),
        max_length=50,
        required=False,
        error_messages={'required': 'Zipcode is a required field.'},
        widget=forms.TextInput(attrs={'size': '10'}))
    country = CountrySelectField(label=_("Country"), required=False)
    mailing_name = forms.CharField(
        label=_("Mailing Name"),
        max_length=120,
        required=False,
        error_messages={'required': 'Mailing name is a required field.'},
        widget=forms.TextInput(attrs={'size': '30'}))

    username = forms.RegexField(
        regex=r'^[\w.@+-]+$',
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_(u'Username'),
        help_text=
        _("Required. Allowed characters are letters, digits, at sign (@), period (.), plus sign (+), dash (-), and underscore (_)."
          ),
        error_messages={
            'invalid':
            'Allowed characters are letters, digits, at sign (@), period (.), plus sign (+), dash (-), and underscore (_).'
        })

    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput(attrs=attrs_dict))
    password2 = forms.CharField(
        label=_("Password (again)"),
        widget=forms.PasswordInput(attrs=attrs_dict),
        help_text=_("Enter the same password as above, for verification."))
    security_level = forms.ChoiceField(initial="user",
                                       choices=(
                                           ('user', 'User'),
                                           ('staff', 'Staff'),
                                           ('superuser', 'Superuser'),
                                       ))
    interactive = forms.ChoiceField(initial=1,
                                    choices=(
                                        (1, 'Interactive'),
                                        (0, 'Not Interactive (no login)'),
                                    ))
    direct_mail = forms.ChoiceField(initial=1,
                                    choices=(
                                        (1, 'Yes'),
                                        (0, 'No'),
                                    ))
    notes = forms.CharField(label=_("Notes"),
                            max_length=1000,
                            required=False,
                            widget=forms.Textarea(attrs={'rows': '3'}))
    admin_notes = forms.CharField(label=_("Admin Notes"),
                                  max_length=1000,
                                  required=False,
                                  widget=forms.Textarea(attrs={'rows': '3'}))
    language = forms.ChoiceField(initial="en", choices=settings.LANGUAGES)
    dob = forms.DateField(required=False,
                          widget=SelectDateWidget(None, range(1920,
                                                              THIS_YEAR)))

    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))

    class Meta:
        model = Profile
        fields = (
            'salutation',
            'first_name',
            'last_name',
            'username',
            'password1',
            'password2',
            'phone',
            'phone2',
            'fax',
            'work_phone',
            'home_phone',
            'mobile_phone',
            'email',
            'email2',
            'company',
            'position_title',
            'position_assignment',
            'display_name',
            'hide_in_search',
            'hide_phone',
            'hide_email',
            'hide_address',
            'initials',
            'sex',
            'mailing_name',
            'address',
            'address2',
            'city',
            'state',
            'zipcode',
            'county',
            'country',
            'url',
            'dob',
            'ssn',
            'spouse',
            'time_zone',
            'language',
            'department',
            'education',
            'student',
            'direct_mail',
            'notes',
            'interactive',
            'allow_anonymous_view',
            'admin_notes',
            'security_level',
            'status_detail',
        )

    def __init__(self, *args, **kwargs):
        if 'user_this' in kwargs:
            self.user_this = kwargs.pop('user_this', None)
        else:
            self.user_this = None

        if 'user_current' in kwargs:
            self.user_current = kwargs.pop('user_current', None)
        else:
            self.user_current = None

        if 'required_fields_list' in kwargs:
            self.required_fields_list = kwargs.pop('required_fields_list',
                                                   None)
        else:
            self.required_fields_list = None

        super(ProfileForm, self).__init__(*args, **kwargs)

        if self.user_this:
            self.fields['first_name'].initial = self.user_this.first_name
            self.fields['last_name'].initial = self.user_this.last_name
            self.fields['username'].initial = self.user_this.username
            self.fields['email'].initial = self.user_this.email

            if self.user_this.is_superuser:
                self.fields['security_level'].initial = "superuser"
            elif self.user_this.is_staff:
                self.fields['security_level'].initial = "staff"
            else:
                self.fields['security_level'].initial = "user"
            if self.user_this.is_active == 1:
                self.fields['interactive'].initial = 1
            else:
                self.fields['interactive'].initial = 0

            del self.fields['password1']
            del self.fields['password2']

            if not self.user_current.profile.is_superuser:
                del self.fields['admin_notes']
                del self.fields['security_level']
                del self.fields['status_detail']

            if self.user_current.profile.is_superuser and self.user_current == self.user_this:
                self.fields['security_level'].choices = (('superuser',
                                                          'Superuser'), )

        if not self.user_current.profile.is_superuser:
            if 'status_detail' in self.fields: self.fields.pop('status_detail')

        # we make first_name, last_name, email, username and password as required field regardless
        # the rest of fields will be decided by the setting - UsersRequiredFields
        if self.required_fields_list:
            for field in self.required_fields_list:
                for myfield in self.fields:
                    if field == self.fields[myfield].label:
                        self.fields[myfield].required = True
                        continue

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.
        """
        try:
            user = User.objects.get(username=self.cleaned_data['username'])
            if self.user_this and user.id == self.user_this.id and user.username == self.user_this.username:
                return self.cleaned_data['username']
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(
            _(u'This username is already taken. Please choose another.'))

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.
        
        """
        if not self.user_this:
            if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
                if self.cleaned_data['password1'] != self.cleaned_data[
                        'password2']:
                    raise forms.ValidationError(
                        _(u'You must type the same password each time'))
        return self.cleaned_data

    def save(self, request, user_edit, *args, **kwargs):
        """
        Create a new user then create the user profile
        """
        username = self.cleaned_data['username']
        email = self.cleaned_data['email']
        params = {
            'first_name': self.cleaned_data['first_name'],
            'last_name': self.cleaned_data['last_name'],
            'email': self.cleaned_data['email'],
        }

        if not self.user_this:
            password = self.cleaned_data['password1']
            new_user = User.objects.create_user(username, email, password)
            self.instance.user = new_user
            update_user(new_user, **params)
        else:
            # for update_subscription
            self.instance.old_email = user_edit.email

            params.update({'username': username})
            update_user(user_edit, **params)

        if not self.instance.id:
            self.instance.creator = request.user
            self.instance.creator_username = request.user.username
        self.instance.owner = request.user
        self.instance.owner_username = request.user.username

        return super(ProfileForm, self).save(*args, **kwargs)
Ejemplo n.º 5
0
class ProfileAdminForm(TendenciBaseForm):

    first_name = forms.CharField(
        label=_("First Name"),
        max_length=100,
        error_messages={'required': 'First Name is a required field.'})
    last_name = forms.CharField(
        label=_("Last Name"),
        max_length=100,
        error_messages={'required': 'Last Name is a required field.'})
    email = EmailVerificationField(
        label=_("Email"),
        error_messages={'required': 'Email is a required field.'})
    email2 = EmailVerificationField(label=_("Secondary Email"), required=False)

    username = forms.RegexField(
        regex=r'^[\w.@+-]+$',
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_(u'Username'),
        help_text=
        _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."
          ))
    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput(attrs=attrs_dict))
    password2 = forms.CharField(
        label=_("Password (again)"),
        widget=forms.PasswordInput(attrs=attrs_dict),
        help_text=_("Enter the same password as above, for verification."))

    security_level = forms.ChoiceField(initial="user",
                                       choices=(
                                           ('user', 'User'),
                                           ('staff', 'Staff'),
                                           ('superuser', 'Superuser'),
                                       ))
    interactive = forms.ChoiceField(initial=1,
                                    choices=(
                                        (1, 'Interactive'),
                                        (0, 'Not Interactive (no login)'),
                                    ))

    language = forms.ChoiceField(initial="en", choices=settings.LANGUAGES)

    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))

    class Meta:
        model = Profile
        fields = (
            'salutation',
            'first_name',
            'last_name',
            'username',
            'password1',
            'password2',
            'phone',
            'phone2',
            'fax',
            'work_phone',
            'home_phone',
            'mobile_phone',
            'email',
            'email2',
            'company',
            'position_title',
            'position_assignment',
            'display_name',
            'hide_in_search',
            'hide_phone',
            'hide_email',
            'hide_address',
            'initials',
            'sex',
            'mailing_name',
            'address',
            'address2',
            'city',
            'state',
            'zipcode',
            'county',
            'country',
            'url',
            'dob',
            'ssn',
            'spouse',
            'time_zone',
            'language',
            'department',
            'education',
            'student',
            'direct_mail',
            'notes',
            'interactive',
            'allow_anonymous_view',
            'admin_notes',
            'security_level',
            'status_detail',
        )

    def __init__(self, *args, **kwargs):
        super(ProfileAdminForm, self).__init__(*args, **kwargs)

        if self.instance.id:
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name
            self.fields['username'].initial = self.instance.user.username
            self.fields['email'].initial = self.instance.user.email

            self.fields['password1'].required = False
            self.fields['password2'].required = False
            self.fields['password1'].widget.attrs['readonly'] = True
            self.fields['password2'].widget.attrs['readonly'] = True

            if self.instance.user.is_superuser:
                self.fields['security_level'].initial = "superuser"
            elif self.instance.user.is_staff:
                self.fields['security_level'].initial = "staff"
            else:
                self.fields['security_level'].initial = "user"
            if self.instance.user.is_active == 1:
                self.fields['interactive'].initial = 1
            else:
                self.fields['interactive'].initial = 0

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.
        
        """
        try:
            user = User.objects.get(
                username__iexact=self.cleaned_data['username'])
            if self.instance.id and user.id == self.instance.user.id:
                return self.cleaned_data['username']
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(
            _(u'This username is already taken. Please choose another.'))

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.
        
        """
        if not self.instance.id:
            if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
                if self.cleaned_data['password1'] != self.cleaned_data[
                        'password2']:
                    raise forms.ValidationError(
                        _(u'You must type the same password each time'))
        return self.cleaned_data

    def save(self, *args, **kwargs):
        """
        Create a new user then create the user profile
        """
        request = kwargs.pop('request', None)
        username = self.cleaned_data['username']
        email = self.cleaned_data['email']
        params = {
            'first_name': self.cleaned_data['first_name'],
            'last_name': self.cleaned_data['last_name'],
            'email': self.cleaned_data['email'],
        }

        if not self.instance.id:
            password = self.cleaned_data['password1']
            new_user = User.objects.create_user(username, email, password)
            self.instance.user = new_user
            update_user(new_user, **params)
        else:
            self.instance.old_email = self.instance.user.email

            params.update({'username': username})
            update_user(self.instance.user, **params)

        if not (request.user == self.instance.user
                and request.user.is_superuser):
            security_level = self.cleaned_data['security_level']
            if security_level == 'superuser':
                self.instance.user.is_superuser = 1
                self.instance.user.is_staff = 1
            elif security_level == 'staff':
                self.instance.user.is_superuser = 0
                self.instance.user.is_staff = 1
            else:
                self.instance.user.is_superuser = 0
                self.instance.user.is_staff = 0

            interactive = self.cleaned_data['interactive']
            try:
                interactive = int(interactive)
            except:
                interactive = 0
            self.instance.user.is_active = interactive

        if not self.instance.id:
            self.instance.creator = request.user
            self.instance.creator_username = request.user.username
        self.instance.owner = request.user
        self.instance.owner_username = request.user.username

        self.instance.user.save()
        self.instance.save()

        return super(ProfileAdminForm, self).save(*args, **kwargs)
Ejemplo n.º 6
0
class MakePaymentForm(forms.ModelForm):
    captcha = CaptchaField(label=_('Type the code below'))
    # TODO: Make check-paid an admin only option
    payment_amount = PriceField(max_digits=10, decimal_places=2)
    payment_method = forms.CharField(
        widget=forms.RadioSelect(choices=(('cc', _('Make Online Payment')), )),
        initial='cc',
    )
    company = forms.CharField(max_length=50,
                              required=False,
                              widget=forms.TextInput(attrs={'size': '30'}))
    address = forms.CharField(max_length=100,
                              required=False,
                              widget=forms.TextInput(attrs={'size': '35'}))
    state = forms.CharField(max_length=50,
                            required=False,
                            widget=forms.TextInput(attrs={'size': '5'}))
    zip_code = forms.CharField(max_length=20,
                               required=False,
                               widget=forms.TextInput(attrs={'size': '10'}))
    referral_source = forms.CharField(
        max_length=200,
        required=False,
        widget=forms.TextInput(attrs={'size': '40'}))
    email = EmailVerificationField(
        label=_("Email"), help_text=_('A valid e-mail address, please.'))
    email_receipt = forms.BooleanField(initial=True)
    country = forms.ChoiceField(label=_('Country'), choices=COUNTRIES)

    class Meta:
        model = MakePayment
        fields = (
            'payment_amount',
            'payment_method',
            'first_name',
            'last_name',
            'company',
            'address',
            'address2',
            'city',
            'state',
            'zip_code',
            'country',
            'phone',
            'email',
            'email_receipt',
            'referral_source',
            'comments',
            'captcha',
        )

    def __init__(self, user, *args, **kwargs):
        super(MakePaymentForm, self).__init__(*args, **kwargs)
        self.initial['country'] = get_setting('site', 'global',
                                              'defaultcountry')
        # populate the user fields
        if user and user.id:
            if 'captcha' in self.fields:
                self.fields.pop('captcha')
            self.fields['first_name'].initial = user.first_name
            self.fields['last_name'].initial = user.last_name
            self.fields['email'].initial = user.email
            try:
                profile = user.get_profile()
                if profile:
                    self.fields['company'].initial = profile.company
                    self.fields['address'].initial = profile.address
                    self.fields['address2'].initial = profile.address2
                    self.fields['city'].initial = profile.city
                    self.fields['state'].initial = profile.state
                    self.fields['zip_code'].initial = profile.zipcode
                    self.fields['country'].initial = profile.country
                    self.fields['phone'].initial = profile.phone
            except:
                pass
Ejemplo n.º 7
0
class NewsForm(TendenciBaseForm):
    body = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style': 'width:100%;'},
        mce_attrs={'storme_app_label': News._meta.app_label,
        'storme_model': News._meta.module_name.lower()}))
    release_dt = SplitDateTimeField(label=_('Release Date/Time'), initial=datetime.now())
    status_detail = forms.ChoiceField(
        choices=(('active', 'Active'), ('inactive', 'Inactive'), ('pending', 'Pending')))
    email = EmailVerificationField(label=_("Email"), required=False)

    photo_upload = forms.FileField(label=_('Thumbnail Image'), required=False, help_text=_('The thumbnail image can be used on your homepage or sidebar if it is setup in your theme. It will not display on the news page.'))
    remove_photo = forms.BooleanField(label=_('Remove the current photo'), required=False)

    group = forms.ModelChoiceField(queryset=Group.objects.filter(status=True, status_detail="active"), required=True, empty_label=None)

    class Meta:
        model = News

        fields = (
        'headline',
        'slug',
        'summary',
        'body',
        'group',
        'photo_upload',
        'source',
        'website',
        'release_dt',
        'timezone',
        'first_name',
        'last_name',
        'phone',
        'fax',
        'email',
        'tags',
        'allow_anonymous_view',
        'syndicate',
        'user_perms',
        'member_perms',
        'group_perms',
        'status',
        'status_detail',
        )

        fieldsets = [('News Information', {
                      'fields': ['headline',
                                 'slug',
                                 'summary',
                                 'body',
                                 'group',
                                 'tags',
                                 'photo_upload',
                                 'source',
                                 'website',
                                 'release_dt',
                                 'timezone',
                                 ],
                      'legend': ''
                      }),
                      ('Contact', {
                      'fields': ['first_name',
                                 'last_name',
                                 'phone',
                                 'fax',
                                 'email',
                                 ],
                        'classes': ['contact'],
                      }),
                      ('Permissions', {
                      'fields': ['allow_anonymous_view',
                                 'user_perms',
                                 'member_perms',
                                 'group_perms',
                                 ],
                      'classes': ['permissions'],
                      }),
                     ('Administrator Only', {
                      'fields': ['syndicate',
                                 'status',
                                 'status_detail'],
                      'classes': ['admin-only'],
                    })]

    def clean_photo_upload(self):
        photo_upload = self.cleaned_data['photo_upload']
        if photo_upload:
            extension = splitext(photo_upload.name)[1]

            # check the extension
            if extension.lower() not in ALLOWED_LOGO_EXT:
                raise forms.ValidationError('The photo must be of jpg, gif, or png image type.')

            # check the image header
            image_type = '.%s' % imghdr.what('', photo_upload.read())
            if image_type not in ALLOWED_LOGO_EXT:
                raise forms.ValidationError('The photo is an invalid image. Try uploading another photo.')

            max_upload_size = get_max_file_upload_size()
            if photo_upload.size > max_upload_size:
                raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(max_upload_size), filesizeformat(photo_upload.size)))

        return photo_upload

    def save(self, *args, **kwargs):
        news = super(NewsForm, self).save(*args, **kwargs)
        if self.cleaned_data.get('remove_photo'):
            news.thumbnail = None
        return news

    def __init__(self, *args, **kwargs):
        super(NewsForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = self.instance.pk
        else:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['group'].initial = Group.objects.get_initial_group_id()

        #if not self.user.profile.is_superuser:
        if self.user and not self.user.profile.is_superuser:
            if 'status' in self.fields:
                self.fields.pop('status')
            if 'status_detail' in self.fields:
                self.fields.pop('status_detail')

        # only show the remove photo checkbox if there is already a thumbnail
        if self.instance.thumbnail:
            self.fields['photo_upload'].help_text = '<input name="remove_photo" id="id_remove_photo" type="checkbox"/> Remove current image: <a target="_blank" href="/files/%s/">%s</a>' % (self.instance.thumbnail.pk, basename(self.instance.thumbnail.file.name))
        else:
            self.fields.pop('remove_photo')
Ejemplo n.º 8
0
class DirectoryForm(TendenciBaseForm):
    body = forms.CharField(required=False,
                           widget=TinyMCE(
                               attrs={'style': 'width:100%'},
                               mce_attrs={
                                   'storme_app_label':
                                   Directory._meta.app_label,
                                   'storme_model':
                                   Directory._meta.module_name.lower()
                               }))

    logo = forms.FileField(
        required=False,
        help_text=_('Company logo. Only jpg, gif, or png images.'))

    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('pending', _('Pending')),
    ))

    list_type = forms.ChoiceField(initial='regular',
                                  choices=(
                                      ('regular', _('Regular')),
                                      ('premium', _('Premium')),
                                  ))
    payment_method = forms.CharField(
        error_messages={'required': _('Please select a payment method.')})

    activation_dt = SplitDateTimeField(initial=datetime.now())
    expiration_dt = SplitDateTimeField(initial=datetime.now())

    email = EmailVerificationField(label=_("Email"), required=False)
    email2 = EmailVerificationField(label=_("Email 2"), required=False)
    country = CountrySelectField(label=_("Country"), required=False)

    pricing = forms.ModelChoiceField(queryset=DirectoryPricing.objects.filter(
        status=True).order_by('duration'),
                                     **request_duration_defaults)

    class Meta:
        model = Directory
        fields = (
            'headline',
            'slug',
            'summary',
            'body',
            'logo',
            'source',
            'timezone',
            'first_name',
            'last_name',
            'address',
            'address2',
            'city',
            'state',
            'zip_code',
            'country',
            'phone',
            'phone2',
            'fax',
            'email',
            'email2',
            'website',
            'tags',
            'pricing',
            'list_type',
            'payment_method',
            'activation_dt',
            'expiration_dt',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_user_edit',
            'syndicate',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [(_('Directory Information'), {
            'fields': [
                'headline',
                'slug',
                'summary',
                'body',
                'logo',
                'tags',
                'source',
                'timezone',
                'activation_dt',
                'pricing',
                'expiration_dt',
            ],
            'legend':
            ''
        }),
                     (_('Payment'), {
                         'fields': ['list_type', 'payment_method'],
                         'classes': ['payment_method'],
                     }),
                     (_('Contact'), {
                         'fields': [
                             'first_name', 'last_name', 'address', 'address2',
                             'city', 'state', 'zip_code', 'country', 'phone',
                             'phone2', 'fax', 'email', 'email2', 'website'
                         ],
                         'classes': ['contact'],
                     }),
                     (_('Permissions'), {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     (_('Administrator Only'), {
                         'fields': ['syndicate', 'status_detail'],
                         'classes': ['admin-only'],
                     })]

    def clean_logo(self):
        logo = self.cleaned_data['logo']
        if logo:
            try:
                extension = splitext(logo.name)[1]

                # check the extension
                if extension.lower() not in ALLOWED_LOGO_EXT:
                    raise forms.ValidationError(
                        _('The logo must be of jpg, gif, or png image type.'))

                # check the image header
                image_type = '.%s' % imghdr.what('', logo.read())
                if image_type not in ALLOWED_LOGO_EXT:
                    raise forms.ValidationError(
                        _('The logo is an invalid image. Try uploading another logo.'
                          ))

                max_upload_size = get_max_file_upload_size()
                if logo.size > max_upload_size:
                    raise forms.ValidationError(
                        _('Please keep filesize under %(max_upload_size)s. Current filesize %(logo_size)s'
                          ) %
                        {
                            'max_upload_size': filesizeformat(max_upload_size),
                            'logo_size': filesizeformat(logo.size)
                        })
            except IOError:
                logo = None

        return logo

    def __init__(self, *args, **kwargs):
        super(DirectoryForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['body'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
            if self.user.profile.is_superuser:
                self.fields['status_detail'].choices = (
                    ('active', _('Active')),
                    ('inactive', _('Inactive')),
                    ('pending', _('Pending')),
                    ('paid - pending approval', _('Paid - Pending Approval')),
                )
        else:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = 0

        if self.instance.logo:
            self.initial['logo'] = self.instance.logo

        if not self.user.profile.is_superuser:
            if 'status_detail' in self.fields: self.fields.pop('status_detail')

        if self.fields.has_key('payment_method'):
            self.fields['payment_method'].widget = forms.RadioSelect(
                choices=get_payment_method_choices(self.user))
        if self.fields.has_key('pricing'):
            self.fields['pricing'].choices = get_duration_choices(self.user)

        self.fields['timezone'].initial = settings.TIME_ZONE

        # expiration_dt = activation_dt + requested_duration
        fields_to_pop = ['expiration_dt']
        if not self.user.profile.is_superuser:
            fields_to_pop += [
                'slug', 'entity', 'allow_anonymous_view', 'user_perms',
                'member_perms', 'group_perms', 'post_dt', 'activation_dt',
                'syndicate', 'status_detail'
            ]

        for f in list(set(fields_to_pop)):
            if f in self.fields:
                self.fields.pop(f)

    def save(self, *args, **kwargs):
        from tendenci.core.files.models import File
        directory = super(DirectoryForm, self).save(*args, **kwargs)

        content_type = ContentType.objects.get(
            app_label=Directory._meta.app_label,
            model=Directory._meta.module_name)

        if self.cleaned_data.has_key('pricing'):
            directory.requested_duration = self.cleaned_data[
                'pricing'].duration

        if self.cleaned_data['logo']:
            file_object, created = File.objects.get_or_create(
                file=self.cleaned_data['logo'],
                defaults={
                    'name': self.cleaned_data['logo'].name,
                    'content_type': content_type,
                    'object_id': directory.pk,
                    'is_public': directory.allow_anonymous_view,
                    'tags': directory.tags,
                })

            directory.logo_file = file_object
            directory.save(log=False)

        # clear logo; if box checked
        if self.cleaned_data['logo'] is False:
            directory.logo_file = None
            directory.save(log=False)
            File.objects.filter(content_type=content_type,
                                object_id=directory.pk).delete()

        return directory
Ejemplo n.º 9
0
class LocationForm(TendenciBaseForm):

    photo_upload = forms.FileField(label=_('Logo'), required=False)
    remove_photo = forms.BooleanField(label=_('Remove the current logo'),
                                      required=False)

    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))

    email = EmailVerificationField(label=_("Email"), required=False)
    country = CountrySelectField(label=_("Country"), required=False)

    class Meta:
        model = Location
        fields = (
            'location_name',
            'description',
            'contact',
            'address',
            'address2',
            'city',
            'state',
            'zipcode',
            'country',
            'phone',
            'fax',
            'email',
            'website',
            'latitude',
            'longitude',
            'photo_upload',
            'hq',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [('Location Information', {
            'fields': [
                'location_name',
                'description',
                'latitude',
                'longitude',
                'photo_upload',
                'hq',
            ],
            'legend':
            ''
        }),
                     ('Contact', {
                         'fields': [
                             'contact', 'address', 'address2', 'city', 'state',
                             'zipcode', 'country', 'phone', 'fax', 'email',
                             'website'
                         ],
                         'classes': ['contact'],
                     }),
                     ('Permissions', {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     ('Administrator Only', {
                         'fields': ['status_detail'],
                         'classes': ['admin-only'],
                     })]

    def __init__(self, *args, **kwargs):
        super(LocationForm, self).__init__(*args, **kwargs)

        if self.user:
            if not self.user.profile.is_superuser:
                if 'status_detail' in self.fields:
                    self.fields.pop('status_detail')

        if self.instance.logo:
            self.fields[
                'photo_upload'].help_text = '<input name="remove_photo" id="id_remove_photo" type="checkbox"/> Remove current image: <a target="_blank" href="/files/%s/">%s</a>' % (
                    self.instance.logo.pk,
                    basename(self.instance.logo.file.name))
        else:
            self.fields.pop('remove_photo')

    def clean_photo_upload(self):
        photo_upload = self.cleaned_data['photo_upload']
        if photo_upload:
            extension = splitext(photo_upload.name)[1]

            # check the extension
            if extension.lower() not in ALLOWED_LOGO_EXT:
                raise forms.ValidationError(
                    'The logo must be of jpg, gif, or png image type.')

            # check the image header
            image_type = '.%s' % imghdr.what('', photo_upload.read())
            if image_type not in ALLOWED_LOGO_EXT:
                raise forms.ValidationError(
                    'The logo is an invalid image. Try uploading another logo.'
                )

            max_upload_size = get_max_file_upload_size()
            if photo_upload.size > max_upload_size:
                raise forms.ValidationError(
                    _('Please keep filesize under %s. Current filesize %s') %
                    (filesizeformat(max_upload_size),
                     filesizeformat(photo_upload.size)))

        return photo_upload

    def save(self, *args, **kwargs):
        location = super(LocationForm, self).save(*args, **kwargs)

        if self.cleaned_data.get('remove_photo'):
            location.logo = None
        return location
Ejemplo n.º 10
0
class LocationForm(TendenciBaseForm):

    status_detail = forms.ChoiceField(
        choices=(('active','Active'),('inactive','Inactive'), ('pending','Pending'),))

    email = EmailVerificationField(label=_("Email"), required=False)

    class Meta:
        model = Location
        fields = (
        'location_name',
        'description',
        'contact',
        'address',
        'address2',
        'city',
        'state',
        'zipcode',
        'country',
        'phone',
        'fax',
        'email',
        'website',
        'latitude',
        'longitude',
        'hq',
        'allow_anonymous_view',
        'user_perms',
        'member_perms',
        'group_perms',
        'status',
        'status_detail',
        )

        fieldsets = [('Location Information', {
                      'fields': ['location_name',
                                 'description',
                                 'latitude',
                                 'longitude',
                                 'hq',
                                 ],
                      'legend': ''
                      }),
                      ('Contact', {
                      'fields': ['contact',
                                 'address',
                                 'address2',
                                 'city',
                                 'state',
                                 'zipcode',
                                 'country',
                                 'phone',
                                 'fax',
                                 'email',
                                 'website'
                                 ],
                        'classes': ['contact'],
                      }),
                      ('Permissions', {
                      'fields': ['allow_anonymous_view',
                                 'user_perms',
                                 'member_perms',
                                 'group_perms',
                                 ],
                      'classes': ['permissions'],
                      }),
                     ('Administrator Only', {
                      'fields': ['status',
                                 'status_detail'], 
                      'classes': ['admin-only'],
                    })]   
           
    def __init__(self, *args, **kwargs): 
        super(LocationForm, self).__init__(*args, **kwargs)

        if not self.user.profile.is_superuser:
            if 'status' in self.fields: self.fields.pop('status')
            if 'status_detail' in self.fields: self.fields.pop('status_detail')
Ejemplo n.º 11
0
class ReliefAssessmentForm(BetterModelForm):
    first_name = forms.CharField(label=_("First Name"), max_length=100,
                                 error_messages={'required': 'First Name is a required field.'})
    last_name = forms.CharField(label=_("Last Name"), max_length=100,
                                error_messages={'required': 'Last Name is a required field.'})
    initials = forms.CharField(label=_("Initial"), max_length=100, required=False)

    phone = forms.CharField(label=_("Contact Phone"), max_length=50)
    phone2 = forms.CharField(label=_("Alternate Phone"), max_length=50, required=False)

    email = EmailVerificationField(label=_("Email"),
                                error_messages={'required': 'Email is a required field.'})
    email2 = EmailVerificationField(label=_("Alternate Email"), required=False)

    dob = forms.DateField(label=_("Date of Birth"), required=False,
                          widget=SelectDateWidget(None, range(THIS_YEAR-100, THIS_YEAR)))
    company = forms.CharField(label=_("Company"), max_length=100, required=False)
    position_title = forms.CharField(label=_("Position Title"), max_length=50, required=False)
    education = forms.CharField(label=_("Education Level"), max_length=100, required=False)

    ethnicity = forms.ChoiceField(label="", required=False,
                                  choices=ETHNICITY_CHOICES,
                                  widget=forms.widgets.RadioSelect)

    case_notes = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':ReliefAssessment._meta.app_label,
        'storme_model':ReliefAssessment._meta.module_name.lower()}))

    items_provided = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':ReliefAssessment._meta.app_label,
        'storme_model':ReliefAssessment._meta.module_name.lower()}))

    class Meta:
        model = ReliefAssessment
        exclude = ('user',)

        fieldsets = [
            ('Personal Information', {
                'fields': ['first_name',
                           'last_name',
                           'initials',
                           'phone',
                           'phone2',
                           'email',
                           'email2',
                           'dob',
                           'id_number',
                           'issuing_authority',
                           'company',
                           'position_title',
                           'education',
                           'health_insurance',
                           'insurance_provider',
                          ],}),
            ('Disaster Area Address', {
                'fields': ['address',
                           'address2',
                           'city',
                           'state',
                           'zipcode',
                           'country',
                          ],}),
            ('Alternate Address', {
                'fields': ['alt_address',
                           'alt_address2',
                           'alt_city',
                           'alt_state',
                           'alt_zipcode',
                           'alt_country',
                          ],}),
            ('Ethnicity', {
                'fields': ['ethnicity',
                           'other_ethnicity',
                          ],}),
            ('How many in your household are', {
                'fields': ['below_2',
                           'between_3_11',
                           'between_12_18',
                           'between_19_59',
                           'above_60',
                          ],}),
            ('Please identify services needed', {
                'fields': ['ssa',
                           'dhs',
                           'children_needs',
                           'toiletries',
                           'employment',
                           'training',
                           'food',
                           'gas',
                           'prescription',
                           'other_service',
                          ],}),
            ('For Internal Use', {
                'fields': ['case_notes',
                           'items_provided',
                          ],}),
        ]

    def __init__(self, *args, **kwargs):
        if 'edit' in kwargs:
            edit = kwargs.pop('edit', True)
        else:
            edit = True
        super(ReliefAssessmentForm, self).__init__(*args, **kwargs)
        if not edit:
            for name, field in self.fields.iteritems():
                field.widget.attrs['disabled'] = True

        if self.instance.pk:
            self.fields['case_notes'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['items_provided'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['email'].initial = self.instance.user.email
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name
            self.fields['initials'].initial = self.instance.user.profile.initials
            self.fields['phone'].initial = self.instance.user.profile.phone
            self.fields['phone2'].initial = self.instance.user.profile.phone2
            self.fields['email2'].initial = self.instance.user.profile.email2
            self.fields['dob'].initial = self.instance.user.profile.dob
            self.fields['company'].initial = self.instance.user.profile.company
            self.fields['position_title'].initial = self.instance.user.profile.position_title
            self.fields['education'].initial = self.instance.user.profile.education
        else:
            self.fields['case_notes'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['items_provided'].widget.mce_attrs['app_instance_id'] = 0

    def clean(self):
        cleaned_data = self.cleaned_data

        if 'ethnicity' in cleaned_data:
            ethnicity = cleaned_data.get("ethnicity")
            other_text = cleaned_data.get("other_ethnicity")
            if ethnicity == 'other' and not other_text:
                raise forms.ValidationError("Please specify your ethnicity on the text box provided.")

        return cleaned_data


    def save(self, *args, **kwargs):
        relief = super(ReliefAssessmentForm, self).save(commit=False)

        user, created = Profile.get_or_create_user(**{
            'email': self.cleaned_data.get('email'),
            'first_name': self.cleaned_data.get('first_name'),
            'last_name': self.cleaned_data.get('last_name'),
        })

        if created:
            profile = user.profile
            profile.initials = self.cleaned_data.get('initials')
            profile.phone = self.cleaned_data.get('phone')
            profile.phone2 = self.cleaned_data.get('phone2')
            profile.email2 = self.cleaned_data.get('email2')
            profile.dob = self.cleaned_data.get('dob')
            profile.company = self.cleaned_data.get('company')
            profile.position_title = self.cleaned_data.get('position_title')
            profile.education = self.cleaned_data.get('education')
            profile.save()

        relief.user = user
        relief.save()
Ejemplo n.º 12
0
class ResumeForm(TendenciBaseForm):

    description = forms.CharField(required=False,
                                  widget=TinyMCE(
                                      attrs={'style': 'width:100%'},
                                      mce_attrs={
                                          'storme_app_label':
                                          Resume._meta.app_label,
                                          'storme_model':
                                          Resume._meta.module_name.lower()
                                      }))

    resume_url = forms.CharField(
        label=_('Resume URL'),
        help_text="Link to an external resume (eg. Google Docs)",
        required=False)

    is_agency = forms.BooleanField(
        label=_('Agency'),
        help_text="Are you an agency posting this resume?",
        required=False)

    requested_duration = forms.ChoiceField(
        label=_('Duration'),
        choices=(
            ('30', '30 Days'),
            ('60', '60 Days'),
            ('90', '90 Days'),
        ),
        help_text="Amount of days you would like your resume to stay up.",
        required=False)

    captcha = CaptchaField()

    contact_email = EmailVerificationField(label=_("Contact email"),
                                           required=False)

    activation_dt = SplitDateTimeField(label=_('Activation Date/Time'),
                                       initial=datetime.now())

    expiration_dt = SplitDateTimeField(label=_('Expriation Date/Time'),
                                       initial=(datetime.now() +
                                                timedelta(days=30)))

    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))

    class Meta:
        model = Resume
        fields = (
            'title',
            'slug',
            'description',
            'resume_url',
            'resume_file',
            'location',
            'skills',
            'experience',
            'education',
            'is_agency',
            'requested_duration',
            'tags',
            'contact_name',
            'contact_address',
            'contact_address2',
            'contact_city',
            'contact_state',
            'contact_zip_code',
            'contact_country',
            'contact_phone',
            'contact_phone2',
            'contact_fax',
            'contact_email',
            'contact_website',
            'captcha',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'activation_dt',
            'expiration_dt',
            'syndicate',
            'status',
            'status_detail',
        )

        fieldsets = [('Resume Information', {
            'fields': [
                'title',
                'slug',
                'description',
                'resume_url',
                'resume_file',
                'location',
                'skills',
                'experience',
                'education',
                'tags',
                'requested_duration',
                'is_agency',
            ],
            'legend':
            ''
        }),
                     ('Contact', {
                         'fields': [
                             'contact_name',
                             'contact_address',
                             'contact_address2',
                             'contact_city',
                             'contact_state',
                             'contact_zip_code',
                             'contact_country',
                             'contact_phone',
                             'contact_phone2',
                             'contact_fax',
                             'contact_email',
                             'contact_website',
                         ],
                         'classes': ['contact'],
                     }),
                     ('Security Code', {
                         'fields': [
                             'captcha',
                         ],
                         'classes': ['captcha'],
                     }),
                     ('Permissions', {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     ('Administrator Only', {
                         'fields': [
                             'activation_dt', 'expiration_dt', 'syndicate',
                             'status', 'status_detail'
                         ],
                         'classes': ['admin-only'],
                     })]

    def __init__(self, *args, **kwargs):
        super(ResumeForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['description'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['description'].widget.mce_attrs['app_instance_id'] = 0

        # adjust fields depending on user status
        fields_to_pop = []
        if not self.user.is_authenticated():
            fields_to_pop += [
                'allow_anonymous_view', 'user_perms', 'member_perms',
                'group_perms', 'activation_dt', 'expiration_dt', 'syndicate',
                'status', 'status_detail'
            ]
        else:
            fields_to_pop += ['captcha']
        if not self.user.profile.is_superuser:
            fields_to_pop += [
                'allow_anonymous_view', 'user_perms', 'member_perms',
                'group_perms', 'activation_dt', 'expiration_dt', 'syndicate',
                'status', 'status_detail'
            ]
        for f in list(set(fields_to_pop)):
            if f in self.fields: self.fields.pop(f)

    def clean_resume_file(self):
        resume = self.cleaned_data['resume_file']
        if resume:
            extension = splitext(resume.name)[1]
            # check the extension
            if extension.lower() not in ALLOWED_FILE_EXT:
                raise forms.ValidationError(
                    'The file must be of doc, docx, pdf, or rtf format.')
        return resume
Ejemplo n.º 13
0
class RegistrationForm(forms.Form):
    """
    Form for registering a new user account.
    
    Validates that the requested username is not already in use, and
    requires the password to be entered twice to catch typos.
    
    Subclasses should feel free to add any additional validation they
    need, but should either preserve the base ``save()`` or implement
    a ``save()`` which accepts the ``profile_callback`` keyword
    argument and passes it through to
    ``RegistrationProfile.objects.create_inactive_user()``.
    
    """
    username = forms.RegexField(regex=r'^\w+$',
                                max_length=30,
                                widget=forms.TextInput(attrs=attrs_dict),
                                label=_(u'username'))
    email = EmailVerificationField(label=_(u'email address'))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
                                                           render_value=False),
                                label=_(u'password'))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
                                                           render_value=False),
                                label=_(u'password (again)'))

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.
        
        """
        try:
            user = User.objects.get(
                username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(
            _(u'This username is already taken. Please choose another.'))

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.
        
        """
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(
                    _(u'You must type the same password each time'))
        return self.cleaned_data

    def save(self, profile_callback=None):
        """
        Create the new ``User`` and ``RegistrationProfile``, and
        returns the ``User``.
        
        This is essentially a light wrapper around
        ``RegistrationProfile.objects.create_inactive_user()``,
        feeding it the form data and a profile callback (see the
        documentation on ``create_inactive_user()`` for details) if
        supplied.
        
        """
        new_user = RegistrationProfile.objects.create_inactive_user(
            username=self.cleaned_data['username'],
            password=self.cleaned_data['password1'],
            email=self.cleaned_data['email'],
            profile_callback=profile_callback)
        return new_user
Ejemplo n.º 14
0
class ArticleForm(TendenciBaseForm):
    body = forms.CharField(required=False,
                           widget=TinyMCE(
                               attrs={'style': 'width:100%'},
                               mce_attrs={
                                   'storme_app_label':
                                   Article._meta.app_label,
                                   'storme_model':
                                   Article._meta.module_name.lower()
                               }))

    release_dt = SplitDateTimeField(label=_('Release Date/Time'),
                                    initial=datetime.now())

    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))
    email = EmailVerificationField(label=_("Email"), required=False)
    group = forms.ModelChoiceField(queryset=Group.objects.filter(
        status=True, status_detail="active"),
                                   required=True,
                                   empty_label=None)

    class Meta:
        model = Article
        fields = (
            'headline',
            'slug',
            'summary',
            'body',
            'source',
            'website',
            'release_dt',
            'timezone',
            'first_name',
            'last_name',
            'phone',
            'fax',
            'email',
            'group',
            'tags',
            'allow_anonymous_view',
            'syndicate',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [('Article Information', {
            'fields': [
                'headline',
                'slug',
                'summary',
                'body',
                'group',
                'tags',
                'source',
                'website',
                'release_dt',
                'timezone',
            ],
            'legend':
            ''
        }),
                     ('Contact', {
                         'fields': [
                             'first_name',
                             'last_name',
                             'phone',
                             'fax',
                             'email',
                         ],
                         'classes': ['contact'],
                     }),
                     ('Permissions', {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     ('Administrator Only', {
                         'fields': ['syndicate', 'status_detail'],
                         'classes': ['admin-only'],
                     })]

    def __init__(self, *args, **kwargs):
        super(ArticleForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['body'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['group'].initial = Group.objects.get_initial_group_id()

        if self.user and not self.user.profile.is_superuser:
            if 'status_detail' in self.fields:
                self.fields.pop('status_detail')
Ejemplo n.º 15
0
class ArticleForm(TendenciBaseForm):
    body = forms.CharField(required=False,
                           widget=TinyMCE(
                               attrs={'style': 'width:100%'},
                               mce_attrs={
                                   'storme_app_label':
                                   Article._meta.app_label,
                                   'storme_model':
                                   Article._meta.module_name.lower()
                               }))

    release_dt = SplitDateTimeField(label=_('Release Date/Time'),
                                    initial=datetime.now())

    contributor_type = forms.ChoiceField(choices=CONTRIBUTOR_CHOICES,
                                         initial=Article.CONTRIBUTOR_AUTHOR,
                                         widget=forms.RadioSelect())

    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))
    email = EmailVerificationField(label=_("Email"), required=False)
    group = forms.ChoiceField(required=True, choices=[])

    class Meta:
        model = Article
        fields = (
            'headline',
            'slug',
            'summary',
            'body',
            'source',
            'website',
            'release_dt',
            'timezone',
            'contributor_type',
            'first_name',
            'last_name',
            'google_profile',
            'phone',
            'fax',
            'email',
            'group',
            'tags',
            'allow_anonymous_view',
            'syndicate',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [('Article Information', {
            'fields': [
                'headline',
                'slug',
                'summary',
                'body',
                'group',
                'tags',
                'source',
                'website',
                'release_dt',
                'timezone',
            ],
            'legend':
            ''
        }),
                     ('Contributor', {
                         'fields': ['contributor_type', 'google_profile'],
                         'classes': ['boxy-grey'],
                     }),
                     ('Author', {
                         'fields': [
                             'first_name',
                             'last_name',
                             'phone',
                             'fax',
                             'email',
                         ],
                         'classes': ['contact'],
                     }),
                     ('Permissions', {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     ('Administrator Only', {
                         'fields': ['syndicate', 'status_detail'],
                         'classes': ['admin-only'],
                     })]

    def __init__(self, *args, **kwargs):
        super(ArticleForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['body'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['group'].initial = Group.objects.get_initial_group_id()

        default_groups = Group.objects.filter(status=True,
                                              status_detail="active")

        if self.user and not self.user.profile.is_superuser:
            if 'status_detail' in self.fields:
                self.fields.pop('status_detail')

            filters = get_query_filters(self.user, 'user_groups.view_group',
                                        **{'perms_field': False})
            groups = default_groups.filter(filters).distinct()
            groups_list = list(groups.values_list('pk', 'name'))

            users_groups = self.user.profile.get_groups()
            for g in users_groups:
                if [g.id, g.name] not in groups_list:
                    groups_list.append([g.id, g.name])
        else:
            groups_list = default_groups.values_list('pk', 'name')

        self.fields['group'].choices = groups_list
        self.fields['google_profile'].help_text = mark_safe(
            GOOGLE_PLUS_HELP_TEXT)
        self.fields['timezone'].initial = settings.TIME_ZONE

    def clean_group(self):
        group_id = self.cleaned_data['group']

        try:
            group = Group.objects.get(pk=group_id)
            return group
        except Group.DoesNotExist:
            raise forms.ValidationError(_('Invalid group selected.'))
Ejemplo n.º 16
0
class NewsForm(TendenciBaseForm):
    body = forms.CharField(required=False,
                           widget=TinyMCE(attrs={'style': 'width:100%;'},
                                          mce_attrs={
                                              'storme_app_label':
                                              News._meta.app_label,
                                              'storme_model':
                                              News._meta.module_name.lower()
                                          }))
    release_dt = SplitDateTimeField(label=_('Release Date/Time'),
                                    initial=datetime.now())
    status_detail = forms.ChoiceField(choices=(('active', _('Active')),
                                               ('inactive', _('Inactive')),
                                               ('pending', _('Pending'))))
    email = EmailVerificationField(label=_("Email"), required=False)

    contributor_type = forms.ChoiceField(choices=CONTRIBUTOR_CHOICES,
                                         initial=News.CONTRIBUTOR_AUTHOR,
                                         widget=forms.RadioSelect())

    photo_upload = forms.FileField(
        label=_('Thumbnail Image'),
        required=False,
        help_text=
        _('The thumbnail image can be used on your homepage or sidebar if it is setup in your theme. It will not display on the news page.'
          ))
    remove_photo = forms.BooleanField(label=_('Remove the current photo'),
                                      required=False)

    group = forms.ChoiceField(required=True, choices=[])

    class Meta:
        model = News

        fields = (
            'headline',
            'slug',
            'summary',
            'body',
            'group',
            'photo_upload',
            'source',
            'website',
            'release_dt',
            'timezone',
            'contributor_type',
            'first_name',
            'last_name',
            'google_profile',
            'phone',
            'fax',
            'email',
            'tags',
            'allow_anonymous_view',
            'syndicate',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [(_('News Information'), {
            'fields': [
                'headline',
                'slug',
                'summary',
                'body',
                'group',
                'tags',
                'photo_upload',
                'source',
                'website',
                'release_dt',
                'timezone',
            ],
            'legend':
            ''
        }),
                     (_('Contributor'), {
                         'fields': ['contributor_type', 'google_profile'],
                         'classes': ['boxy-grey'],
                     }),
                     (_('Author'), {
                         'fields': [
                             'first_name',
                             'last_name',
                             'phone',
                             'fax',
                             'email',
                         ],
                         'classes': ['contact'],
                     }),
                     (_('Permissions'), {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     (_('Administrator Only'), {
                         'fields': ['syndicate', 'status_detail'],
                         'classes': ['admin-only'],
                     })]

    def clean_photo_upload(self):
        photo_upload = self.cleaned_data['photo_upload']
        if photo_upload:
            extension = splitext(photo_upload.name)[1]

            # check the extension
            if extension.lower() not in ALLOWED_LOGO_EXT:
                raise forms.ValidationError(
                    _('The photo must be of jpg, gif, or png image type.'))

            # check the image header
            image_type = '.%s' % imghdr.what('', photo_upload.read())
            if image_type not in ALLOWED_LOGO_EXT:
                raise forms.ValidationError(
                    _('The photo is an invalid image. Try uploading another photo.'
                      ))

            max_upload_size = get_max_file_upload_size()
            if photo_upload.size > max_upload_size:
                raise forms.ValidationError(
                    _('Please keep filesize under %(max_upload_size)s. Current filesize %(upload_size)s'
                      ) % {
                          'max_upload_size': filesizeformat(max_upload_size),
                          'upload_size': filesizeformat(photo_upload.size)
                      })

        return photo_upload

    def clean_group(self):
        group_id = self.cleaned_data['group']

        try:
            group = Group.objects.get(pk=group_id)
            return group
        except Group.DoesNotExist:
            raise forms.ValidationError(_('Invalid group selected.'))

    def save(self, *args, **kwargs):
        news = super(NewsForm, self).save(*args, **kwargs)
        if self.cleaned_data.get('remove_photo'):
            news.thumbnail = None
        return news

    def __init__(self, *args, **kwargs):
        super(NewsForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['body'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['group'].initial = Group.objects.get_initial_group_id()

        default_groups = Group.objects.filter(status=True,
                                              status_detail="active")

        #if not self.user.profile.is_superuser:
        if self.user and not self.user.profile.is_superuser:
            if 'status_detail' in self.fields:
                self.fields.pop('status_detail')

            filters = get_query_filters(self.user, 'user_groups.view_group',
                                        **{'perms_field': False})
            groups = default_groups.filter(filters).distinct()
            groups_list = list(groups.values_list('pk', 'name'))

            users_groups = self.user.profile.get_groups()
            for g in users_groups:
                if [g.id, g.name] not in groups_list:
                    groups_list.append([g.id, g.name])
        else:
            groups_list = default_groups.values_list('pk', 'name')

        self.fields['group'].choices = groups_list
        self.fields['google_profile'].help_text = mark_safe(
            GOOGLE_PLUS_HELP_TEXT)
        self.fields['timezone'].initial = settings.TIME_ZONE

        # only show the remove photo checkbox if there is already a thumbnail
        if self.instance.thumbnail:
            self.fields[
                'photo_upload'].help_text = '<input name="remove_photo" id="id_remove_photo" type="checkbox"/> Remove current image: <a target="_blank" href="/files/%s/">%s</a>' % (
                    self.instance.thumbnail.pk,
                    basename(self.instance.thumbnail.file.name))
        else:
            self.fields.pop('remove_photo')