Exemplo n.º 1
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.º 2
0
class UserMembershipForm(TendenciBaseForm):
    join_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 = MembershipDefault
        fields = (
            'member_number',
            'membership_type',
            'join_dt',
            'expire_dt',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status',
            'status_detail',
        )

        fieldsets = [(_('Membership Information'), {
            'fields': [
                'member_number',
                'membership_type',
                'join_dt',
                'expire_dt',
            ],
            'legend':
            ''
        }),
                     (_('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(UserMembershipForm, self).__init__(*args, **kwargs)
Exemplo n.º 3
0
class MarkAsPaidForm(forms.ModelForm):
    amount = PriceField(
        label=_('Amount'),
        initial=0.0,
        min_value=0,
    )
    payment_method = forms.CharField(
        label=_('payment method'),
        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 = 'Invoice {} for {}({})'.format(
                    instance.pk, invoice_object, invoice_object.pk)

        return instance
Exemplo n.º 4
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.model_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())
    syndicate = forms.BooleanField(label=_('Include in RSS feed'),
                                   required=False,
                                   initial=True)
    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.'))

    def clean_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False
Exemplo n.º 5
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.model_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 = CustomCatpchaField(label=_('Type the code below'))

    contact_email = EmailVerificationField(label=_("Contact email"), required=False)
    contact_country = CountrySelectField(label=_("Contact country"), 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)))

    syndicate = forms.BooleanField(label=_('Include in RSS Feed'), required=False, initial=True)

    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',
        'awards',
        '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_detail',
       )

        fieldsets = [(_('Resume Information'), {
                      'fields': ['title',
                                 'slug',
                                 'description',
                                 'resume_url',
                                 'resume_file',
                                 'location',
                                 'skills',
                                 'experience',
                                 'awards',
                                 '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_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_detail'
            ]
        for f in list(set(fields_to_pop)):
            if f in self.fields: self.fields.pop(f)

    def clean_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False

    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

    def clean(self):
        cleaned_data = super(ResumeForm, self).clean()

        print(self.errors)

        return cleaned_data
Exemplo n.º 6
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.model_name.lower()
                               }))

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

    syndicate = forms.BooleanField(label=_('Include in RSS Feed'),
                                   required=False,
                                   initial=True)

    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_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False

    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 clean_headline(self):
        """
        remove extra leading and trailing white spaces
        """
        return self.cleaned_data.get('headline', '').strip()

    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'] = forms.ChoiceField(
                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.apps.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.model_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.º 7
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,
    )
    syndicate = forms.BooleanField(label=_('Include in RSS Feed'),
                                   required=False,
                                   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.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 clean_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False

    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.º 8
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.model_name.lower()
                                      }))

    captcha = CaptchaField(label=_('Type the code below'))

    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())

    syndicate = forms.BooleanField(label=_('Include in RSS Feed'),
                                   required=False,
                                   initial=True)

    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)
    contact_country = CountrySelectField(label=_("Contact country"),
                                         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_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_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_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_detail'
            ]

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

    def clean_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False

    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.º 9
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.model_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)
    syndicate = forms.BooleanField(label=_('Include in RSS Feed'),
                                   required=False,
                                   initial=True)

    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 clean_syndicate(self):
        """
        clean method for syndicate added due to the update
        done on the field BooleanField -> NullBooleanField
        NOTE: BooleanField is converted to NullBooleanField because
        some Boolean data has value of None than False. This was updated
        on Django 1.6. BooleanField cannot have a value of None.
        """
        data = self.cleaned_data.get('syndicate', False)
        if data:
            return True
        else:
            return False

    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')
Exemplo n.º 10
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.º 11
0
class DiscountForm(TendenciBaseForm):

    value = PriceField(
        label=_('Discount Value'),
        max_digits=10,
        decimal_places=2,
        help_text=_('Enter discount value as a positive number.'))

    class Meta:
        model = Discount
        fields = (
            'discount_code',
            'value',
            'start_dt',
            'end_dt',
            'never_expires',
            'cap',
            'apps',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            '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_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 self.user and not self.user.profile.is_superuser:
            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)
        if 'apps' in self.fields:
            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