Exemplo n.º 1
0
class EventLogSearchForm(BetterForm):
    start_dt = SplitDateTimeField(label=_('Start Date/Time'),
                                  initial=INITIAL_START_DT,
                                  required=False)
    end_dt = SplitDateTimeField(label=_('End Date/Time'),
                                initial=INITIAL_END_DT,
                                required=False)
    request_method = forms.ChoiceField(required=False,
                                       choices=((
                                           'all',
                                           'ALL',
                                       ), (
                                           'post',
                                           'POST',
                                       ), (
                                           'get',
                                           'GET',
                                       )))
    event_id = forms.IntegerField(required=False)
    source = forms.CharField(required=False)
    object_id = forms.CharField(required=False)
    user_ip_address = forms.CharField(required=False)
    user_id = forms.IntegerField(required=False)
    user_name = forms.CharField(required=False)
    session_id = forms.CharField(required=False)
    application = forms.CharField(required=False)
    action = forms.CharField(required=False)

    class Meta:
        fields = (
            'start_dt',
            'end_dt',
            'request_method',
            'event_id',
            'source',
            'object_id'
            'user_ip_address',
            'user_id',
            'user_name',
            'session_id',
            'application',
            'action',
        )

        fieldsets = [
            ('', {
                'fields': ['start_dt', 'end_dt', 'request_method', 'event_id'],
                'legend': ''
            }),
            ('Advanced Options', {
                'fields': [
                    'user_id', 'user_name', 'user_ip_address', 'session_id',
                    'source', 'object_id', 'application', 'action'
                ],
                'legend':
                'Advanced Options'
            }),
        ]
Exemplo n.º 2
0
class NoticeLogSearchForm(forms.Form):
    start_dt = SplitDateTimeField(label=_('Sent Start Date/Time'),
        initial=(datetime.now()-timedelta(days=30)), required=False)
    end_dt = SplitDateTimeField(label=_('Sent End Date/Time'),
        initial=datetime.now(), required=False)
    notice_id = forms.ChoiceField(required=False)
    
    def __init__(self, *args, **kwargs):
        super(NoticeLogSearchForm, self).__init__(*args, **kwargs)
        self.fields['notice_id'].choices = get_membership_notice_choices()
Exemplo n.º 3
0
class UserMembershipForm(TendenciBaseForm):
    subscribe_dt = SplitDateTimeField(label=_('Subscribe Date/Time'),
                                      initial=datetime.datetime.now())
    expire_dt = SplitDateTimeField(label=_('Expire Date/Time'), required=False)
    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))

    class Meta:
        model = Membership
        fields = (
            'user',
            'member_number',
            'membership_type',
            'subscribe_dt',
            'expire_dt',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status',
            'status_detail',
        )

        fieldsets = [('Membership Information', {
            'fields': [
                'user',
                'member_number',
                'membership_type',
                'subscribe_dt',
                'expire_dt',
            ],
            'legend':
            ''
        }),
                     ('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):
        super(UserMembershipForm, self).__init__(*args, **kwargs)
        self.fields['user'].widget = forms.HiddenInput()
Exemplo n.º 4
0
class MarkAsPaidForm(forms.ModelForm):

    payment_method = forms.CharField(
        max_length=20,
        widget=forms.Select(choices=PAYMENT_METHODS))

    submit_dt = SplitDateTimeField(
        label=_('Submit Date and Time'),
        initial=datetime.now())

    class Meta:
        model = Payment
        fields = (
            'amount',
            'payment_method',
            'submit_dt',
        )

    def save(self, user, invoice, *args, **kwargs):
        """
        Save payment, bind invoice instance.
        Set payment fields (e.g. name, description)
        """
        instance = super(MarkAsPaidForm, self).save(*args, **kwargs)

        instance.method = self.cleaned_data['payment_method']

        instance.invoice = invoice
        instance.first_name = invoice.bill_to_first_name
        instance.last_name = invoice.bill_to_last_name
        instance.email = invoice.bill_to_email
        instance.status_detail = 'approved'

        instance.creator = user
        instance.creator_username = user.username
        instance.owner = user
        instance.owner_username = user.username

        instance.save()

        invoice_object = invoice.get_object()

        if invoice_object:
            if hasattr(invoice_object, 'get_payment_description'):
                instance.description = invoice_object.get_payment_description(invoice)
            if not instance.description:
                instance.description = 'Tendenci Invoice {} for {}({})'.format(
                    instance.pk, invoice_object, invoice_object.pk)

        return instance
Exemplo n.º 5
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
Exemplo n.º 6
0
class StoryForm(TendenciBaseForm):
    fullstorylink = forms.CharField(label=_("Full Story Link"),
                                    required=False,
                                    max_length=300)
    start_dt = SplitDateTimeField(label=_('Start Date/Time'),
                                  initial=datetime.now())
    end_dt = SplitDateTimeField(label=_('End Date/Time'),
                                initial=END_DT_INITIAL)
    expires = forms.BooleanField(
        label=_('Expires'),
        required=False,
        help_text=
        _('Check if you want this story to expire and be sure to specify the end date.'
          ),
        initial=False,
    )
    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('pending', _('Pending')),
    ))
    photo_upload = forms.FileField(label=_('Photo'), required=False)
    remove_photo = forms.BooleanField(label=_('Remove the current photo'),
                                      required=False)
    group = forms.ChoiceField(required=True, choices=[])

    class Meta:
        model = Story

        fields = (
            'title',
            'content',
            'full_story_link',
            'link_title',
            'rotator',
            'tags',
            'photo_upload',
            'start_dt',
            'end_dt',
            'expires',
            'group',
            'syndicate',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [(_('Story Information'), {
            'fields': [
                'title',
                'content',
                'photo_upload',
                'full_story_link',
                'link_title',
                'rotator',
                'tags',
                'start_dt',
                'end_dt',
                'expires',
                'group',
            ],
            'legend':
            ''
        }),
                     (_('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 __init__(self, *args, **kwargs):
        super(StoryForm, self).__init__(*args, **kwargs)
        if self.instance.image:
            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.image.pk,
                    basename(self.instance.image.file.name))
        else:
            self.fields.pop('remove_photo')

        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

    def save(self, *args, **kwargs):
        story = super(StoryForm, self).save(*args, **kwargs)
        if self.cleaned_data.get('remove_photo'):
            story.image = None
        return story
Exemplo n.º 7
0
class StoryAdminForm(TendenciBaseForm):
    start_dt = SplitDateTimeField(label=_('Start Date/Time'),
                                  initial=datetime.now())
    end_dt = SplitDateTimeField(label=_('End Date/Time'),
                                initial=END_DT_INITIAL)
    expires = forms.BooleanField(
        label=_('Expires'),
        required=False,
        help_text=
        _('Check if you want this story to expire and be sure to specify the end date.'
          ),
        initial=False,
    )
    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('pending', _('Pending')),
    ))
    photo_upload = forms.FileField(label=_('Photo'), required=False)
    remove_photo = forms.BooleanField(label=_('Remove the current photo'),
                                      required=False)

    class Meta:
        model = Story

        fields = (
            'title',
            'content',
            'full_story_link',
            'link_title',
            'rotator',
            'tags',
            'photo_upload',
            'start_dt',
            'end_dt',
            'expires',
            'syndicate',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [(_('Story Information'), {
            'fields': [
                'title', 'content', 'photo_upload', 'full_story_link',
                'link_title', 'rotator', 'tags', 'start_dt', 'end_dt',
                'expires'
            ],
            'legend':
            ''
        }),
                     (_('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 __init__(self, *args, **kwargs):
        super(StoryAdminForm, self).__init__(*args, **kwargs)
        if self.instance.image:
            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.image.pk,
                    basename(self.instance.image.file.name))
        else:
            self.fields.pop('remove_photo')

    def save(self, *args, **kwargs):
        story = super(StoryAdminForm, self).save(*args, **kwargs)
        if self.cleaned_data.get('remove_photo'):
            story.image = None
        return story
Exemplo n.º 8
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')
Exemplo n.º 9
0
class CorpMembForm(forms.ModelForm):
    status_detail = forms.ChoiceField(
        choices=(('active', 'Active'),
                 ('pending', 'Pending'),
                 ('paid - pending approval', 'Paid - Pending Approval'),
                 ('admin hold', 'Admin Hold'),
                 ('inactive', 'Inactive'),
                 ('expired', 'Expired'),))
    join_dt = SplitDateTimeField(label=_('Join Date/Time'),
        initial=datetime.now())
    expiration_dt = SplitDateTimeField(
                       label=_('Expiration Date/Time'),
                       required=False,
                       help_text='Not specified = Never expires')

    class Meta:
        model = CorporateMembership
        exclude = ('corp_app', 'guid', 'renewal', 'invoice',
                   'renew_dt', 'secret_code',
                   'approved', 'approved_denied_dt',
                   'approved_denied_user',
                   'creator_username',
                   'owner', 'owner_username',
                   'anonymous_creator')

    def __init__(self, corp_app, field_objs, *args, **kwargs):
        """
            Dynamically build the form fields.
        """
        self.corp_app = corp_app
        self.field_objs = field_objs
        super(CorpMembForm, self).__init__(*args, **kwargs)

        for field in field_objs:
            if field.field_type not in ['section_break', 'page_break']:
                if field.field_name:
                    field_key = field.field_name
                else:
                    field_key = "field_%s" % field.id

                # if field is display only, remove it from the form
                # for example, on the edit page, we
                # set corporate_membership_type
                # and payment_method as the display only fields
                if hasattr(field, 'display_only') and field.display_only:
                    del self.fields[field_key]
                else:
                    # get field class and set field initial
                    self.fields[field_key] = field.get_field_class()
                    if ((not field.field_name) \
                        or field.field_name == 'authorized_domains') \
                        and self.instance:
                        initial = field.get_value(self.instance)
                        if field.field_type in [
                            'MultipleChoiceField/django.forms.CheckboxSelectMultiple',
                            'MultipleChoiceField']:
                            if initial:
                                self.fields[field_key].initial = [
                                item.strip() for item in initial.split(',')]
                        else:
                            self.fields[field_key].initial = initial

        #self.fields['captcha'] = CaptchaField(label=_('Type the code below'))

    def clean_corporate_membership_type(self):
        if self.cleaned_data['corporate_membership_type']:
            return CorporateMembershipType.objects.get(
            pk=int(self.cleaned_data['corporate_membership_type']))
        return self.cleaned_data['corporate_membership_type']

    def clean_secret_code(self):
        secret_code = self.cleaned_data['secret_code']
        if secret_code:
            # check if this secret_code is available to ensure the uniqueness
            corp_membs = CorporateMembership.objects.filter(
                                secret_code=secret_code)
            if self.instance:
                corp_membs = corp_membs.exclude(id=self.instance.id)
            if corp_membs:
                raise forms.ValidationError(
            _("This secret code is already taken. Please use a different one.")
            )
        return self.cleaned_data['secret_code']

    def clean_payment_method(self):
        if self.cleaned_data['payment_method']:
            return PaymentMethod.objects.get(
                pk=int(self.cleaned_data['payment_method'])
                )
        return self.cleaned_data['payment_method']

    def save(self, user, **kwargs):
        """
            Create a CorporateMembership instance and related
            CorpFieldEntry instances for each form field.
        """
        corporate_membership = super(CorpMembForm, self).save(commit=False)
        corporate_membership.corp_app = self.corp_app
        creator_owner = user

        if not self.instance.pk:
            mode = 'add'
        else:
            mode = 'edit'

        if mode == 'add':
            anonymous_creator = kwargs.get('creator', None)
            if anonymous_creator:
                corporate_membership.anonymous_creator = anonymous_creator
            if not isinstance(creator_owner, User):
                # if anonymous is creating the corporate membership
                # temporarily use the first admin, the creator will be assigned 
                # back to the real user on approval
                tmp_user = User.objects.filter(is_staff=1, is_active=1)[0]
                creator_owner = tmp_user

            corporate_membership.creator = creator_owner
            corporate_membership.creator_username = creator_owner.username

            if not user.profile.is_superuser:
                corporate_membership.status = 1
                corporate_membership.status_detail = 'pending'
                corporate_membership.join_dt = datetime.now()

        corporate_membership.owner = creator_owner
        corporate_membership.owner_username = creator_owner.username

            # calculate the expiration dt
        corporate_membership.save()
        for field_obj in self.field_objs:
            if (not field_obj.field_name) and field_obj.field_type not in [
                'section_break', 'page_break']:
                field_key = "field_%s" % field_obj.id
                value = self.cleaned_data[field_key]
                if value and self.fields[field_key].widget.needs_multipart_form:
                    if not type(value) is unicode:
                        value = fs.save(join("forms",
                                        str(uuid4()),
                                        value.name),
                                        value)
                # if the value is a list convert is to a comma delimited string
                if isinstance(value, list):
                    value = ','.join(value)
                if not value:
                    value = ''

                if hasattr(field_obj, 'entry') and field_obj.entry:
                    field_obj.entry.value = value
                    field_obj.entry.save()
                else:
                    corporate_membership.fields.create(field_id=field_obj.id,
                                                       value=value)

        # update authorized domain if needed
        if self.corp_app.authentication_method == 'email':
            update_auth_domains(corporate_membership,
                                self.cleaned_data['authorized_domains'])

        return corporate_membership
Exemplo n.º 10
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
Exemplo n.º 11
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'),
    ))

    class Meta:
        model = Article
        fields = (
            'headline',
            'slug',
            'summary',
            'body',
            '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 = [('Article Information', {
            'fields': [
                'headline',
                'slug',
                'summary',
                'body',
                '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', '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

        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')
Exemplo n.º 12
0
class StoryForm(TendenciBaseForm):
    fullstorylink = forms.CharField(label=_("Full Story Link"), required=False, max_length=300)
    start_dt = SplitDateTimeField(label=_('Start Date/Time'), initial=datetime.now())
    end_dt = SplitDateTimeField(label=_('End Date/Time'), initial=END_DT_INITIAL)
    expires = forms.BooleanField(
        label=_('Expires'),
        required=False,
        help_text=_('Uncheck if you want this story to never expire'),
        initial=True,
    )
    status_detail = forms.ChoiceField(
        choices=(('active','Active'),('inactive','Inactive'), ('pending','Pending'),))
    photo_upload = forms.FileField(label=_('Photo'), required=False)
    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 = Story

        fields = (
            'title',
            'content',
            'full_story_link',
            'link_title',
            'tags',
            'photo_upload',
            'start_dt',
            'end_dt',
            'expires',
            'group',
            'syndicate',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status',
            'status_detail',
        )

        fieldsets = [('Story Information', {
                      'fields': ['title',
                                 'content',
                                 'photo_upload',
                                 'full_story_link',
                                 'link_title',
                                 'tags',
                                 'start_dt',
                                 'end_dt',
                                 'expires',
                                 'group',
                                 ],
                      'legend': ''
                      }),
                      ('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.')

        return photo_upload
                 
    def __init__(self, *args, **kwargs):
        super(StoryForm, self).__init__(*args, **kwargs)
        self.fields['group'].initial = Group.objects.get_initial_group_id()
        if self.instance.image:
            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.image.pk, basename(self.instance.image.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')

    def save(self, *args, **kwargs):
        story = super(StoryForm, self).save(*args, **kwargs)
        if self.cleaned_data.get('remove_photo'):
            story.image = None
        return story
Exemplo n.º 13
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.'))
Exemplo n.º 14
0
class EventLogSearchForm(BetterForm):
    start_dt = SplitDateTimeField(label=_('Start Date/Time'),
                                  initial=INITIAL_START_DT,
                                  required=False)
    end_dt = SplitDateTimeField(label=_('End Date/Time'),
                                initial=INITIAL_END_DT,
                                required=False)
    request_method = forms.ChoiceField(
        required=False,
        choices=REQUEST_CHOICES,
        help_text=
        _('GET = whether a page/item was viewed. POST = an item was edited or added'
          ))

    object_id = forms.CharField(
        required=False,
        help_text=_(
            "This is the ID Tendenci uses for all objects. "
            "This is the number you sometimes see in URLs. For example, "
            "for the event at http://tendenci.com/events/173/, the object ID is 173."
        ))

    user_ip_address = forms.CharField(required=False)
    user_id = forms.IntegerField(required=False)
    user_name = forms.CharField(required=False)

    application = forms.ChoiceField(
        required=False,
        choices=APP_CHOICES,
        help_text=_("These are the different modules like Pages or Articles."))

    action = forms.CharField(
        required=False,
        help_text=_(
            "These are the actions within the python commands at view.py. "
            "Some examples of actions are search and edit, for example."))

    class Meta:
        fields = (
            'start_dt',
            'end_dt',
            'request_method',
            'object_id'
            'user_ip_address',
            'user_id',
            'user_name',
            'application',
            'action',
        )

        fieldsets = [
            ('', {
                'fields': [
                    'start_dt',
                    'end_dt',
                    'request_method',
                ],
                'legend': ''
            }),
            (_('Advanced Options'), {
                'fields': [
                    'user_id', 'user_name', 'user_ip_address', 'object_id',
                    'application', 'action'
                ],
                'legend':
                'Advanced Options'
            }),
        ]
Exemplo n.º 15
0
class DiscountForm(TendenciBaseForm):
    class Meta:
        model = Discount
        fields = (
            'discount_code',
            'value',
            'start_dt',
            'end_dt',
            'never_expires',
            'cap',
            'apps',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'status',
            'status_detail',
        )

        fieldsets = [('Discount Information', {
            'fields': [
                'discount_code',
                'value',
                'cap',
                'never_expires',
                'apps',
                'start_dt',
                'end_dt',
            ],
            'legend':
            ''
        }),
                     ('Permissions', {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     ('Administrator Only', {
                         'fields': ['status', 'status_detail'],
                         'classes': ['admin-only'],
                     })]

    start_dt = SplitDateTimeField(label=_('Start Date/Time'),
                                  initial=datetime.now())
    end_dt = SplitDateTimeField(label=_('End Date/Time'),
                                initial=END_DT_INITIAL)
    status_detail = forms.ChoiceField(choices=(
        ('active', 'Active'),
        ('inactive', 'Inactive'),
        ('pending', 'Pending'),
    ))

    def __init__(self, *args, **kwargs):
        super(DiscountForm, 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')

        MODELS_WITH_DISCOUNT = ['registrationconfiguration', 'membershipset']
        content_types = ContentType.objects.filter(
            model__in=MODELS_WITH_DISCOUNT)
        self.fields['apps'].choices = ((c.id, c.app_label)
                                       for c in content_types)

    def clean_discount_code(self):
        data = self.cleaned_data['discount_code']
        try:
            discount = Discount.objects.get(discount_code=data)
        except Discount.DoesNotExist:
            return data
        if not discount == self.instance:
            raise forms.ValidationError(
                'There a discount for this code already exists.')
        return data

    def clean(self):
        cleaned_data = self.cleaned_data
        start_dt = cleaned_data.get("start_dt")
        end_dt = cleaned_data.get("end_dt")

        if start_dt > end_dt:
            errors = self._errors.setdefault("end_dt", ErrorList())
            errors.append(u"This cannot be \
                earlier than the start date.")

        # Always return the full collection of cleaned data.
        return cleaned_data
Exemplo n.º 16
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()

    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',
            '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',
                '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)
Exemplo n.º 17
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
Exemplo n.º 18
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')