Пример #1
0
class StaffForm(TendenciBaseForm):

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

    cv = forms.CharField(
        label='CV',
        required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
            mce_attrs={'storme_app_label':Staff._meta.app_label,
            'storme_model':Staff._meta.model_name.lower()}))

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

    def clean_photo(self):
        photo = self.cleaned_data['photo']
        if photo:
            extension = splitext(photo.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.read())
            if image_type not in ALLOWED_LOGO_EXT:
                raise forms.ValidationError('The photo is an invalid image. Try uploading another photo.')

        return photo

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

    class Meta:
        model = Staff
        fields = (
            'name',
            'slug',
            'department',
            'positions',
            'biography',
            'cv',
            'email',
            'phone',
            'personal_sites',
            'tags',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'member_perms',
            'status_detail',
        )
Пример #2
0
class ChapterAdminForm(TendenciBaseForm):
    mission = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Chapter._meta.app_label,
        'storme_model':Chapter._meta.model_name.lower()}))
    content = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Chapter._meta.app_label,
        'storme_model':Chapter._meta.model_name.lower()}))
    notes = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Chapter._meta.app_label,
        'storme_model':Chapter._meta.model_name.lower()}))

    group = forms.ModelChoiceField(queryset=Group.objects.filter(status=True, status_detail="active").order_by('name'))

    status_detail = forms.ChoiceField(
        choices=(('active','Active'),('inactive','Inactive'), ('pending','Pending'),))
    photo_upload = forms.FileField(label=_('Featured Image'), required=False,
                                   validators=[FileValidator(allowed_extensions=('.jpg', '.jpeg', '.gif', '.png'))],)

    class Meta:
        model = Chapter

        fields = (
        'title',
        'slug',
        'entity',
        'group',
        'mission',
        'content',
        'notes',
        'photo_upload',
        'contact_name',
        'contact_email',
        'join_link',
        'tags',
        'allow_anonymous_view',
        'syndicate',
        'status_detail',
        )

    def __init__(self, *args, **kwargs):
        super(ChapterAdminForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['mission'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['content'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['notes'].widget.mce_attrs['app_instance_id'] = self.instance.pk
        else:
            self.fields['mission'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['content'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['notes'].widget.mce_attrs['app_instance_id'] = 0
        if self.instance.featured_image:
            self.fields['photo_upload'].help_text = 'Current image: <a target="_blank" href="/files/%s/">%s</a>' % (self.instance.featured_image.pk, basename(self.instance.featured_image.file.name))
            self.fields['photo_upload'].required = False
Пример #3
0
class StudyGroupAdminForm(TendenciBaseForm):
    mission = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':StudyGroup._meta.app_label,
        'storme_model':StudyGroup._meta.model_name.lower()}))
    content = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':StudyGroup._meta.app_label,
        'storme_model':StudyGroup._meta.model_name.lower()}))
    notes = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':StudyGroup._meta.app_label,
        'storme_model':StudyGroup._meta.model_name.lower()}))

    group = forms.ModelChoiceField(required=False, queryset=Group.objects.filter(status=True, status_detail="active").order_by('name'))

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

    class Meta:
        model = StudyGroup

        fields = (
        'title',
        'slug',
        'group',
        'mission',
        'content',
        'notes',
        'contact_name',
        'contact_email',
        'join_link',
        'tags',
        'allow_anonymous_view',
        'syndicate',
        'status_detail',
        )

    def __init__(self, *args, **kwargs):
        super(StudyGroupAdminForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['mission'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['content'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['notes'].widget.mce_attrs['app_instance_id'] = self.instance.pk
        else:
            self.fields['mission'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['content'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['notes'].widget.mce_attrs['app_instance_id'] = 0
Пример #4
0
class NoticeForm(forms.ModelForm):
    notice_time_type = NoticeTimeTypeField(label=_('When to Send'),
                                           widget=ChapterNoticeTimeTypeWidget)
    email_content = forms.CharField(
        widget=TinyMCE(attrs={'style': 'width:70%'},
                       mce_attrs={
                           'storme_app_label': Notice._meta.app_label,
                           'storme_model': Notice._meta.model_name.lower()
                       }),
        help_text=_("Click here to view available tokens"))

    class Meta:
        model = Notice
        fields = (
            'notice_name',
            'notice_time_type',
            'chapter',
            'membership_type',
            'subject',
            'content_type',
            'sender',
            'sender_display',
            'email_content',
            'status',
            'status_detail',
        )

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

        initial_list = []
        if self.instance.pk:
            initial_list.append(str(self.instance.num_days))
            initial_list.append(str(self.instance.notice_time))
            initial_list.append(str(self.instance.notice_type))
        else:
            initial_list = ['0', 'attimeof', 'apply']

        self.fields['notice_time_type'].initial = initial_list
        self.fields['email_content'].help_text = get_notice_token_help_text(
            self.instance)

    def clean_notice_time_type(self):
        value = self.cleaned_data['notice_time_type']

        data_list = value.split(',')
        d = dict(zip(['num_days', 'notice_time', 'notice_type'], data_list))

        try:
            d['num_days'] = int(d['num_days'])
        except:
            raise forms.ValidationError(
                _("Num days must be a numeric number."))
        return value
Пример #5
0
class BoxForm(TendenciBaseForm):
    content = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Box._meta.app_label,
        'storme_model':Box._meta.model_name.lower()}))

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

    class Meta:
        model = Box
        fields = (
            'title',
            'content',
            'group',
            'tags',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
            )

    def __init__(self, *args, **kwargs):
        super(BoxForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['content'].widget.mce_attrs['app_instance_id'] = self.instance.pk
        else:
            self.fields['content'].widget.mce_attrs['app_instance_id'] = 0
Пример #6
0
class VideoForm(TendenciBaseForm):

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

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

    clear_image = forms.BooleanField(required=False)

    class Meta:
        model = Video
        fields = (
            'title',
            'slug',
            'category',
            'video_type',
            'image',
            'video_url',
            'tags',
            'description',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'member_perms',
            'status_detail',
        )

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

    def clean_video_url(self):
        value = self.cleaned_data.get('video_url')
        # Get embedded object from URL
        obj = client.oembed(value)
        if not value:
            raise forms.ValidationError('You must enter a URL')
        if obj.get('error'):
            raise forms.ValidationError(
                'This url is not supported by embed.ly')
        return value

    def save(self, *args, **kwargs):
        video = super(VideoForm, self).save(*args, **kwargs)
        if self.cleaned_data['clear_image']:
            video.image.delete()
        return video
Пример #7
0
class EmailForm(forms.ModelForm):
    STATUS_CHOICES = (
        ('active', _('Active')),
        ('inactive', _('Inactive')),
    )
    subject = forms.CharField(max_length=255,
                              widget=forms.TextInput(attrs={'size': '50'}))
    recipient = forms.CharField(max_length=255,
                                required=False,
                                widget=forms.Textarea(attrs={'rows': '3'}))
    status_detail = forms.ChoiceField(choices=STATUS_CHOICES)

    body = forms.CharField(required=False,
                           widget=TinyMCE(attrs={'style': 'width:80%'},
                                          mce_attrs={
                                              'storme_app_label':
                                              Email._meta.app_label,
                                              'storme_model':
                                              Email._meta.model_name.lower()
                                          }))
    sender = forms.EmailField(
        required=True,
        help_text=_('Sender e-mail address'),
    )

    class Meta:
        model = Email
        fields = (
            'content_type',
            'subject',
            'body',
            'sender',
            'sender_display',
            'reply_to',
            'recipient',
            #'status',
            'status_detail',
        )

    def __init__(self, *args, **kwargs):
        super(EmailForm, 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
        # add form-control class
        for k in self.fields:
            self.fields[k].widget.attrs['class'] = 'form-control'

    def save(self, user=None, *args, **kwargs):
        if user and user.id:
            if not self.instance.id:
                self.instance.creator = user
                self.instance.creator_username = user.username
            self.instance.owner = user
            self.instance.owner_username = user.username

        return super(EmailForm, self).save(*args, **kwargs)
Пример #8
0
class CaseStudyForm(TendenciBaseForm):
    overview = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':CaseStudy._meta.app_label,
        'storme_model':CaseStudy._meta.model_name.lower()}))

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

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

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

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

    class Meta:
        model = CaseStudy
        fields = (
            'client',
            'slug',
            'overview',
            'execution',
            'results',
            'tags',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'member_perms',
            'status_detail',
        )
Пример #9
0
class HelpFileAdminForm(TendenciBaseForm):
    answer = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':HelpFile._meta.app_label,
        'storme_model':HelpFile._meta.model_name.lower()}))

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

    status_detail = forms.ChoiceField(choices=(('draft',_('Draft')),('active',_('Active'))))

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

    class Meta:
        model = HelpFile
        fields = (
            'question',
            'slug',
            'answer',
            'group',
            'level',
            'topics',
            'is_faq',
            'is_featured',
            'is_video',
            'syndicate',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

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

    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
Пример #10
0
class EmergencyAnnouncementAdminForm(TendenciBaseForm):

    content = forms.CharField(
        widget=TinyMCE(attrs={'style': 'width:100%'},
        mce_attrs={'storme_app_label': EmergencyAnnouncement._meta.app_label,
        'storme_model': EmergencyAnnouncement._meta.model_name.lower()}))

    class Meta:
        model = EmergencyAnnouncement
        fields = ('title', 'content', 'enabled', 'allow_anonymous_view',
                  'user_perms', 'member_perms', 'group_perms')

    def __init__(self, *args, **kwargs):
        super(EmergencyAnnouncementAdminForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['content'].widget.mce_attrs['app_instance_id'] = self.instance.pk
        else:
            self.fields['content'].widget.mce_attrs['app_instance_id'] = 0
Пример #11
0
class EmailInvoiceForm(FormControlWidgetMixin, forms.ModelForm):
    subject = forms.CharField(widget=forms.TextInput(
        attrs={'style': 'width:100%;padding:5px 0;'}))
    recipient = forms.EmailField(label=_('Recipient'))
    cc = forms.EmailField(label=_('CC'), required=False)
    body = forms.CharField(widget=TinyMCE(attrs={'style': 'width:100%'},
                                          mce_attrs={
                                              'storme_app_label':
                                              Email._meta.app_label,
                                              'storme_model':
                                              Email._meta.model_name.lower()
                                          }),
                           label=_('Email Content'))
    attachment = forms.BooleanField(label=_('Attach PDF?'),
                                    required=False,
                                    initial=True)

    class Meta:
        model = Email
        fields = (
            'subject',
            'recipient',
            'cc',
            'body',
        )

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

        self.fields['recipient'].widget.attrs['placeholder'] = _(
            'Email Address')
        self.fields['cc'].widget.attrs['placeholder'] = _('Email Address')
Пример #12
0
class EmailChapterMemberForm(FormControlWidgetMixin, forms.ModelForm):
    subject = forms.CharField(widget=forms.TextInput(
        attrs={'style': 'width:100%;padding:5px 0;'}))
    body = forms.CharField(widget=TinyMCE(attrs={'style': 'width:100%'},
                                          mce_attrs={
                                              'storme_app_label':
                                              Email._meta.app_label,
                                              'storme_model':
                                              Email._meta.model_name.lower()
                                          }),
                           label=_('Email Content'),
                           help_text=_("""Available tokens:
                    <ul><li>{{ first_name }}</li>
                    <li>{{ last_name }}</li>
                    <li>{{ chapter_name }}</li>
                    <li>{{ view_url }}</li>
                    <li>{{ edit_url }}</li>
                    <li>{{ site_url }}</li>
                    <li>{{ site_display_name }}</li></ul>"""))

    class Meta:
        model = Email
        fields = (
            'subject',
            'body',
            'sender_display',
            'reply_to',
        )

    def __init__(self, *args, **kwargs):
        super(EmailChapterMemberForm, self).__init__(*args, **kwargs)
        if self.instance.id:
            self.fields['body'].widget.mce_attrs[
                'app_instance_id'] = self.instance.id
        else:
            self.fields['body'].widget.mce_attrs['app_instance_id'] = 0
Пример #13
0
class FormAdminForm(TendenciBaseForm):
    status_detail = forms.ChoiceField(choices=(
        ('draft', _('Draft')),
        ('published', _('Published')),
    ))

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

    response = forms.CharField(
        required=False,
        label=_('Confirmation Text'),
        widget=TinyMCE(attrs={'style': 'width:100%'},
                       mce_attrs={
                           'storme_app_label': Form._meta.app_label,
                           'storme_model': Form._meta.model_name.lower()
                       }),
        help_text=
        _("Optionally, after submission, display a page with this text. Alternately, specify a Completion URL."
          ))

    email_text = forms.CharField(required=False,
                                 label=_('Email Text to Submitter'),
                                 widget=TinyMCE(
                                     attrs={'style': 'width:100%'},
                                     mce_attrs={
                                         'storme_app_label':
                                         Form._meta.app_label,
                                         'storme_model':
                                         Form._meta.model_name.lower()
                                     }))

    template_choices = [('', _('None')), ('default.html', _('Default')),
                        ('forms/base.html', _('Forms Base'))]
    template_choices += get_template_list()
    template = forms.ChoiceField(choices=template_choices, required=False)
    group = forms.ChoiceField(required=True, choices=[])

    class Meta:
        model = Form
        fields = (
            'title',
            'slug',
            'intro',
            'response',
            'group',
            'template',
            'send_email',  # removed per ed's request, added back per Aaron's request 2011-10-14
            'email_text',
            'subject_template',
            'completion_url',
            'email_from',
            'email_copies',
            'user_perms',
            'member_perms',
            'group_perms',
            'allow_anonymous_view',
            'status_detail',
            'custom_payment',
            'recurring_payment',
            'payment_methods',
            'intro_position',
            'fields_position',
            'pricing_position',
            'intro_name',
            'fields_name',
            'pricing_name',
        )

    def __init__(self, *args, **kwargs):
        super(FormAdminForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['intro'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
            self.fields['response'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
            if self.instance.intro_name:
                self.fields['intro'].label = self.instance.intro_name
        else:
            self.fields['intro'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['response'].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")
        self.fields['group'].choices = default_groups.values_list('pk', 'name')

        position_fields = [
            'intro_position', 'fields_position', 'pricing_position'
        ]
        for field in position_fields:
            self.fields[field].widget.attrs['class'] = 'position_field'

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

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

    def clean_slug(self):
        slug = slugify(self.cleaned_data['slug'])
        i = 0
        while True:
            if i > 0:
                if i > 1:
                    slug = slug.rsplit("-", 1)[0]
                slug = "%s-%s" % (slug, i)
            match = Form.objects.filter(slug=slug)
            if self.instance:
                match = match.exclude(pk=self.instance.pk)
            if not match:
                break
            i += 1
        return slug
Пример #14
0
class HelpFileForm(TendenciBaseForm):
    answer = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':HelpFile._meta.app_label,
        'storme_model':HelpFile._meta.model_name.lower()}))

    status_detail = forms.ChoiceField(
        choices=(('draft',_('Draft')),('active',_('Active'))))

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

    #topics = forms.MultipleChoiceField(required=True, widget=widgets.CheckboxSelectMultiple())

    class Meta:
        model = HelpFile
        fields = (
            'question',
            'slug',
            'answer',
            'level',
            'topics',
            'is_faq',
            'is_featured',
            'is_video',
            'syndicate',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

        fieldsets = [(_('Help File Information'), {
                      'fields': ['question',
                                 'slug',
                                 'answer',
                                 'level',
                                 'topics',
                                 ],
                      'legend': ''
                      }),
                      (_('Flags'), {
                      'fields': ['is_faq',
                                 'is_featured',
                                 'is_video',
                                 ],
                        'classes': ['flags'],
                      }),
                      (_('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(HelpFileForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['answer'].widget.mce_attrs['app_instance_id'] = self.instance.pk
        else:
            self.fields['answer'].widget.mce_attrs['app_instance_id'] = 0

        if not self.user.profile.is_superuser:
            if 'status_detail' in self.fields: self.fields.pop('status_detail')
            if 'allow_anonymous_view' in self.fields: self.fields.pop('allow_anonymous_view')
            if 'user_perms' in self.fields: self.fields.pop('user_perms')
            if 'member_perms' in self.fields: self.fields.pop('member_perms')
            if 'group_perms' in self.fields: self.fields.pop('group_perms')
            if 'syndicate' in self.fields: self.fields.pop('syndicate')

    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
Пример #15
0
class ChapterForm(TendenciBaseForm):
    mission = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Chapter._meta.app_label,
        'storme_model':Chapter._meta.model_name.lower()}))
    content = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Chapter._meta.app_label,
        'storme_model':Chapter._meta.model_name.lower()}))
    notes = forms.CharField(required=False,
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Chapter._meta.app_label,
        'storme_model':Chapter._meta.model_name.lower()}))
    photo_upload = forms.FileField(label=_('Featured Image'), required=False,
                                   validators=[FileValidator(allowed_extensions=('.jpg', '.jpeg', '.gif', '.png'))],)


    class Meta:
        model = Chapter
        fields = (
        'title',
        'slug',
        'entity',
        'group',
        'mission',
        'content',
        'notes',
        'sponsors',
        'photo_upload',
        'contact_name',
        'contact_email',
        'join_link',
        'tags',
        'allow_anonymous_view',
        'syndicate',
        'status_detail',
        )
        fieldsets = [('Chapter Information', {
                      'fields': ['title',
                                 'slug',
                                 'entity',
                                 'group',
                                 'mission',
                                 'content',
                                 'notes',
                                 'sponsors',
                                 'photo_upload',
                                 'contact_name',
                                 'contact_email',
                                 'join_link',
                                 'tags'
                                 ],
                      'legend': '',
                      }),
                      ('Permissions', {
                      'fields': ['allow_anonymous_view',
                                 'user_perms',
                                 'member_perms',
                                 'group_perms',
                                 ],
                      'classes': ['permissions'],
                      }),
                     ('Administrator Only', {
                      'fields': ['syndicate',
                                 'status_detail'],
                      'classes': ['admin-only'],
                    })]

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

    def __init__(self, *args, **kwargs):
        super(ChapterForm, self).__init__(*args, **kwargs)
        if self.instance.featured_image:
            self.fields['photo_upload'].help_text = 'Current image: <a target="_blank" href="/files/%s/">%s</a>' % (self.instance.featured_image.pk, basename(self.instance.featured_image.file.name))
        if self.instance.pk:
            self.fields['mission'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['content'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['notes'].widget.mce_attrs['app_instance_id'] = self.instance.pk
        else:
            self.fields['mission'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['content'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['notes'].widget.mce_attrs['app_instance_id'] = 0
            
    def save(self, *args, **kwargs):
        chapter = super(ChapterForm, self).save(*args, **kwargs)
        # save photo
        if 'photo_upload' in self.cleaned_data:
            photo = self.cleaned_data['photo_upload']
            if photo:
                chapter.save(photo=photo)
        return chapter
Пример #16
0
class TestimonialForm(TendenciBaseForm):
    status_detail = forms.ChoiceField(choices=(('active','Active'),('inactive','Inactive')))
    photo_upload = forms.FileField(label=('Photo'), required=False)
    remove_photo = forms.BooleanField(label=('Remove the current photo'), required=False)

    new_mce_attrs = {
        'plugins': "paste",
        'theme_advanced_buttons1': "bold,italic,|,link,unlink,|,pastetext,|,undo,redo",
        'theme_advanced_buttons2': "",
        'theme_advanced_buttons3': "",
    }
    testimonial = forms.CharField(
        widget=TinyMCE(attrs={'style':'width:100%'},
                       mce_attrs=new_mce_attrs), required=False)

    class Meta:
        model = Testimonial
        fields = (
            'first_name',
            'last_name',
            'photo_upload',
            'testimonial',
            'tags',
            'city',
            'state',
            'country',
            'email',
            'company',
            'title',
            'website',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'member_perms',
            'status',
            'status_detail',
        )

    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(TestimonialForm, 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):
        testimonial = super(TestimonialForm, self).save(*args, **kwargs)
        if self.cleaned_data.get('remove_photo'):
            testimonial.image = None
            testimonial.save()
        return testimonial
Пример #17
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 = CustomCatpchaField(label=_('Type the code below'))

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

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

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

    expiration_dt = forms.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.ChoiceField(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)
    cat = forms.ModelChoiceField(label=_("Category"),
                                      queryset=JobCategory.objects.filter(parent=None),
                                      empty_label="-----------",
                                      required=False)
    sub_cat = forms.ModelChoiceField(label=_("Subcategory"),
                                          queryset=JobCategory.objects.none(),
                                          empty_label=_("Please choose a category first"),
                                          required=False)

    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',
            'cat',
            'sub_cat'
        )

        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'],
            }),
            (_('Category'), {
                    'fields': ['cat',
                               'sub_cat'
                               ],
                    'classes': ['boxy-grey job-category'],
                  }),
            (_('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()

        # cat and sub_cat
        if self.user.profile.is_superuser:
            self.fields['sub_cat'].help_text = mark_safe('<a href="{0}">{1}</a>'.format(
                                        reverse('admin:jobs_category_changelist'),
                                        _('Manage Categories'),))
        if self.instance and self.instance.pk:
            self.fields['sub_cat'].queryset = JobCategory.objects.filter(
                                                        parent=self.instance.cat)
        if args:
            post_data = args[0]
        else:
            post_data = None
        if post_data:
            cat = post_data.get('cat', '0')
            if cat and cat != '0' and cat != u'':
                cat = JobCategory.objects.get(pk=int(cat))
                self.fields['sub_cat'].queryset = JobCategory.objects.filter(parent=cat)

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

        if 'payment_method' in self.fields:
            choices=get_payment_method_choices(self.user)
            self.fields['payment_method'].widget = forms.RadioSelect(choices=choices)
            self.fields['payment_method'].choices = choices
            #self.fields['payment_method'].widget = forms.RadioSelect(choices=choices)
            if choices and len(choices) == 1:
                self.fields['payment_method'].initial = choices[0][0]

        # 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
Пример #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.model_name.lower()
                                          }))
    release_dt = forms.SplitDateTimeField(label=_('Release Date/Time'))
    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)

    groups = forms.MultipleChoiceField(
        required=True,
        choices=[],
        help_text=
        _('Hold down "Control", or "Command" on a Mac, to select more than one.'
          ))

    class Meta:
        model = News

        fields = (
            'headline',
            'slug',
            'summary',
            'body',
            'groups',
            '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',
                'groups',
                '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_groups(self):
        group_ids = self.cleaned_data['groups']
        groups = []
        for group_id in group_ids:
            try:
                group = Group.objects.get(pk=group_id)
                groups.append(group)
            except Group.DoesNotExist:
                raise forms.ValidationError(_('Invalid group selected.'))
        return groups

    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['groups'].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 not self.user.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['groups'].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')
        self.fields['release_dt'].initial = datetime.now()
Пример #19
0
class ReliefAssessmentForm(BetterModelForm):
    first_name = forms.CharField(label=_("First Name"), max_length=100,
                                 error_messages={'required': 'First Name is a required field.'})
    last_name = forms.CharField(label=_("Last Name"), max_length=100,
                                error_messages={'required': 'Last Name is a required field.'})
    # initials = forms.CharField(label=_("Initial"), max_length=100, required=False)

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

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

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

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

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

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

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

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

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

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

    def clean(self):
        cleaned_data = self.cleaned_data

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

        return cleaned_data

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

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

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

        relief.user = user
        relief.save()
Пример #20
0
class PageAdminForm(TendenciBaseForm):
    content = forms.CharField(required=False,
                              widget=TinyMCE(attrs={'style': 'width:100%'},
                                             mce_attrs={
                                                 'storme_app_label':
                                                 Page._meta.app_label,
                                                 'storme_model':
                                                 Page._meta.model_name.lower()
                                             }))

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

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

    template_choices = [('default.html', _('Default'))]
    template_choices += get_template_list()
    template = forms.ChoiceField(choices=template_choices)

    meta_title = forms.CharField(required=False)
    meta_description = forms.CharField(
        required=False,
        widget=forms.widgets.Textarea(attrs={'style': 'width:100%'}))
    meta_keywords = forms.CharField(
        required=False,
        widget=forms.widgets.Textarea(attrs={'style': 'width:100%'}))
    meta_canonical_url = forms.CharField(required=False)

    class Meta:
        model = Page
        fields = (
            'title',
            'slug',
            'content',
            'group',
            'tags',
            'template',
            'meta_title',
            'meta_description',
            'meta_keywords',
            'meta_canonical_url',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'member_perms',
            'syndicate',
            'status_detail',
        )

    def __init__(self, *args, **kwargs):
        super(PageAdminForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['content'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
            if self.instance.meta:
                self.fields['meta_title'].initial = self.instance.meta.title
                self.fields[
                    'meta_description'].initial = self.instance.meta.description
                self.fields[
                    'meta_keywords'].initial = self.instance.meta.keywords
                self.fields[
                    'meta_canonical_url'].initial = self.instance.meta.canonical_url
        else:
            self.fields['content'].widget.mce_attrs['app_instance_id'] = 0

    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(self):
        cleaned_data = super(PageAdminForm, self).clean()
        slug = cleaned_data.get('slug')

        # Check if duplicate slug from different page (i.e. different guids)
        # Case 1: Page is edited
        if self.instance:
            guid = self.instance.guid
            if Page.objects.filter(slug=slug).exclude(guid=guid).exists():
                self._errors['slug'] = self.error_class(
                    [_('Duplicate value for slug.')])
                del cleaned_data['slug']
        # Case 2: Add new Page
        else:
            if Page.objects.filter(slug=slug).exists():
                self._errors['slug'] = self.error_class(
                    [_('Duplicate value for slug.')])
                del cleaned_data['slug']

        return cleaned_data
Пример #21
0
class PageForm(TendenciBaseForm):
    header_image = forms.ImageField(required=False)
    remove_photo = forms.BooleanField(
        label=_('Remove the current header image'), required=False)

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

    contributor_type = forms.ChoiceField(choices=CONTRIBUTOR_CHOICES,
                                         initial=Page.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'))))

    tags = forms.CharField(
        required=False,
        help_text=mark_safe('<a href="/tags/" target="_blank">%s</a>' %
                            _('Open All Tags list in a new window')))

    template = forms.ChoiceField(choices=[])

    class Meta:
        model = Page
        fields = (
            'title',
            'slug',
            'content',
            'tags',
            'template',
            'group',
            'contributor_type',
            'allow_anonymous_view',
            'syndicate',
            'user_perms',
            'group_perms',
            'member_perms',
            'status_detail',
        )

        fieldsets = [(_('Page Information'), {
            'fields': [
                'title', 'slug', 'content', 'tags', 'header_image', 'template',
                'group'
            ],
            'legend':
            ''
        }),
                     (_('Contributor'), {
                         'fields': [
                             'contributor_type',
                         ],
                         'classes': ['boxy-grey'],
                     }),
                     (_('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(PageForm, self).__init__(*args, **kwargs)
        if self.instance.header_image:
            self.fields[
                'header_image'].help_text = '<input name="remove_photo" id="id_remove_photo" type="checkbox"/> %s: <a target="_blank" href="/files/%s/">%s</a>' % (
                    _('Remove current image'), self.instance.header_image.pk,
                    basename(self.instance.header_image.file.name))
        else:
            self.fields.pop('remove_photo')

        if self.instance.pk:
            self.fields['content'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['content'].widget.mce_attrs['app_instance_id'] = 0

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

        self.fields['template'].choices = [('default.html', _('Default'))
                                           ] + get_template_list()

    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(self):
        cleaned_data = super(PageForm, self).clean()
        slug = cleaned_data.get('slug')

        # Check if duplicate slug from different page (i.e. different guids)
        # Case 1: Page is edited
        if self.instance:
            guid = self.instance.guid
            if Page.objects.filter(slug=slug).exclude(guid=guid).exists():
                self._errors['slug'] = self.error_class(
                    [_('Duplicate value for slug.')])
                del cleaned_data['slug']
        # Case 2: Add new Page
        else:
            if Page.objects.filter(slug=slug).exists():
                self._errors['slug'] = self.error_class(
                    [_('Duplicate value for slug.')])
                del cleaned_data['slug']

        return cleaned_data

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

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

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

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

        return header_image

    def save(self, *args, **kwargs):
        page = super(PageForm, self).save(*args, **kwargs)
        if self.cleaned_data.get('remove_photo'):
            page.header_image = None
        return page
Пример #22
0
class VideoForm(TendenciBaseForm):
    release_dt = forms.DateTimeField(label=_('Release Date/Time'),
                                     initial=datetime.now())
    description = forms.CharField(required=False,
                                  widget=TinyMCE(
                                      attrs={'style': 'width:100%'},
                                      mce_attrs={
                                          'storme_app_label':
                                          Video._meta.app_label,
                                          'storme_model':
                                          Video._meta.model_name.lower()
                                      }))

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

    clear_image = forms.BooleanField(required=False)

    class Meta:
        model = Video
        fields = (
            'title',
            'slug',
            'category',
            'video_type',
            'image',
            'video_url',
            'tags',
            'description',
            'release_dt',
            'allow_anonymous_view',
            'user_perms',
            'group_perms',
            'member_perms',
            'status_detail',
        )

    def __init__(self, *args, **kwargs):
        super(VideoForm, self).__init__(*args, **kwargs)
        self.embedly_403 = False
        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
        self.fields['release_dt'].widget = widgets.AdminSplitDateTime()

    def clean(self, *args, **kwargs):
        super(VideoForm, self).clean(*args, **kwargs)
        if self.embedly_403:
            if not self.cleaned_data.get('image'):
                raise forms.ValidationError(
                    'Please provide a thumbnail of your video in the image upload field.'
                )
        return self.cleaned_data

    def clean_video_url(self):
        video_url = self.cleaned_data.get('video_url')

        if not video_url:
            raise forms.ValidationError('You must enter a URL')

        if self.instance and self.instance.video_url == video_url:
            # the video_url is not changed, let it go
            return video_url

        # Get embedded object from URL
        client = get_embedly_client()
        obj = client.oembed(video_url)
        if obj.get('error'):
            if obj.get('error_code') != 403:
                raise forms.ValidationError(
                    'This url is not supported by embed.ly')
            else:
                # if youbube video, we can get the thumbnail from youtube API
                if 'www.youtube.com' not in video_url:
                    self.embedly_403 = True
        return video_url

    def save(self, *args, **kwargs):
        video = super(VideoForm, self).save(*args, **kwargs)
        if self.cleaned_data['clear_image']:
            video.image.delete()
        return video
Пример #23
0
class CommitteeForm(TendenciBaseForm):
    mission = forms.CharField(required=False,
                              widget=TinyMCE(
                                  attrs={'style': 'width:100%'},
                                  mce_attrs={
                                      'storme_app_label':
                                      Committee._meta.app_label,
                                      'storme_model':
                                      Committee._meta.model_name.lower()
                                  }))
    content = forms.CharField(required=False,
                              widget=TinyMCE(
                                  attrs={'style': 'width:100%'},
                                  mce_attrs={
                                      'storme_app_label':
                                      Committee._meta.app_label,
                                      'storme_model':
                                      Committee._meta.model_name.lower()
                                  }))
    notes = forms.CharField(required=False,
                            widget=TinyMCE(
                                attrs={'style': 'width:100%'},
                                mce_attrs={
                                    'storme_app_label':
                                    Committee._meta.app_label,
                                    'storme_model':
                                    Committee._meta.model_name.lower()
                                }))

    class Meta:
        model = Committee
        fields = (
            'title',
            'slug',
            'group',
            'mission',
            'content',
            'notes',
            'sponsors',
            'contact_name',
            'contact_email',
            'join_link',
            'tags',
            'allow_anonymous_view',
            'syndicate',
            'status_detail',
        )
        fieldsets = [('Committee Information', {
            'fields': [
                'title', 'slug', 'group', 'mission', 'content', 'notes',
                'sponsors', 'contact_name', 'contact_email', 'join_link',
                'tags'
            ],
            'legend':
            '',
        }),
                     ('Permissions', {
                         'fields': [
                             'allow_anonymous_view',
                             'user_perms',
                             'member_perms',
                             'group_perms',
                         ],
                         'classes': ['permissions'],
                     }),
                     ('Administrator Only', {
                         'fields': ['syndicate', 'status_detail'],
                         'classes': ['admin-only'],
                     })]

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

    def __init__(self, *args, **kwargs):
        super(CommitteeForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['mission'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
            self.fields['content'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
            self.fields['notes'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['mission'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['content'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['notes'].widget.mce_attrs['app_instance_id'] = 0
Пример #24
0
class FormAdminForm(TendenciBaseForm):
    status_detail = forms.ChoiceField(
        choices=(('draft',_('Draft')),('published',_('Published')),))

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

    response = forms.CharField(required=False, label=_('Confirmation Text'),
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Form._meta.app_label,
        'storme_model':Form._meta.model_name.lower()}))
    
    email_text = forms.CharField(required=False, label=_('Confirmation Text'),
        widget=TinyMCE(attrs={'style':'width:100%'},
        mce_attrs={'storme_app_label':Form._meta.app_label,
        'storme_model':Form._meta.model_name.lower()}))

    template = forms.ChoiceField(choices=template_choices, required=False)

    class Meta:
        model = Form
        fields = ('title',
                  'slug',
                  'intro',
                  'response',
                  'template',
                  'send_email', # removed per ed's request, added back per Aaron's request 2011-10-14
                  'email_text',
                  'subject_template',
                  'completion_url',
                  'email_from',
                  'email_copies',
                  'user_perms',
                  'member_perms',
                  'group_perms',
                  'allow_anonymous_view',
                  'status_detail',
                  'custom_payment',
                  'recurring_payment',
                  'payment_methods',
                  'intro_position',
                  'fields_position',
                  'pricing_position',
                  'intro_name',
                  'fields_name',
                  'pricing_name',
                 )

    def __init__(self, *args, **kwargs):
        super(FormAdminForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['intro'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['response'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            if self.instance.intro_name:
                self.fields['intro'].label = self.instance.intro_name
        else:
            self.fields['intro'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['response'].widget.mce_attrs['app_instance_id'] = 0

        position_fields = ['intro_position', 'fields_position', 'pricing_position']
        for field in position_fields:
            self.fields[field].widget.attrs['class'] = 'position_field'


    def clean_slug(self):
        slug = slugify(self.cleaned_data['slug'])
        i = 0
        while True:
            if i > 0:
                if i > 1:
                    slug = slug.rsplit("-", 1)[0]
                slug = "%s-%s" % (slug, i)
            match = Form.objects.filter(slug=slug)
            if self.instance:
                match = match.exclude(pk=self.instance.pk)
            if not match:
                break
            i += 1
        return slug
Пример #25
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. LinkedIn)"),
        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=_("Email"), required=False)
    contact_country = CountrySelectField(label=_("Country"), required=False)
    contact_address = forms.CharField(label=_("Address"), required=False)
    contact_address2 = forms.CharField(label=_("Address2"), required=False)
    contact_city = forms.CharField(label=_("City"), required=False)
    contact_zip_code = forms.CharField(label=_("Zip code"), required=False)
    contact_country = forms.CharField(label=_("Country"), required=False)
    contact_phone = forms.CharField(label=_("Phone"), required=False)
    contact_phone2 = forms.CharField(label=_("Phone2"), required=False)
    contact_fax = forms.CharField(label=_("Fax"), required=False)
    contact_website = forms.CharField(label=_("Website"), required=False)

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

    expiration_dt = forms.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',
            'industry',
            'location',
            'skills',
            'experience',
            'awards',
            'education',
            'is_agency',
            'requested_duration',
            'tags',
            'first_name',
            'last_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',
                'industry',
                'location',
                'skills',
                'experience',
                'awards',
                'education',
                'tags',
                'requested_duration',
                'is_agency',
            ],
            'legend':
            ''
        }),
                     (_('Contact'), {
                         'fields': [
                             'first_name',
                             'last_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)
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True

        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'
            ]

            # Populate contact info for non-superuser
            self.fields['first_name'].initial = self.user.first_name
            self.fields['last_name'].initial = self.user.last_name
            self.fields['contact_address'].initial = self.user.profile.address
            self.fields[
                'contact_address2'].initial = self.user.profile.address2
            self.fields['contact_city'].initial = self.user.profile.city
            self.fields['contact_state'].initial = self.user.profile.state
            self.fields['contact_zip_code'].initial = self.user.profile.zipcode
            self.fields['contact_country'].initial = self.user.profile.country
            self.fields['contact_phone'].initial = self.user.profile.phone
            self.fields['contact_phone2'].initial = self.user.profile.phone2
            self.fields['contact_fax'].initial = self.user.profile.fax
            self.fields['contact_email'].initial = self.user.email
            self.fields['contact_website'].initial = self.user.profile.url

        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
Пример #26
0
class DirectoryForm(TendenciBaseForm):
    body = forms.CharField(label=_("Description"),
                           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 = forms.SplitDateTimeField(initial=datetime.now())
    expiration_dt = forms.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)

    cat = forms.ModelChoiceField(
        label=_("Category"),
        queryset=DirectoryCategory.objects.filter(parent=None),
        empty_label="-----------",
        required=False)
    sub_cat = forms.ModelChoiceField(
        label=_("Subcategory"),
        queryset=DirectoryCategory.objects.none(),
        empty_label=_("Please choose a category first"),
        required=False)

    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',
            'cat',
            'sub_cat',
            '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'],
                     }),
                     (_('Category'), {
                         'fields': ['cat', 'sub_cat'],
                         'classes': ['boxy-grey job-category'],
                     }),
                     (_('Administrator Only'), {
                         'fields': ['syndicate', 'status_detail'],
                         'classes': ['admin-only'],
                     })]

    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 'payment_method' in self.fields:
            self.fields['payment_method'] = forms.ChoiceField(
                widget=forms.RadioSelect,
                choices=get_payment_method_choices(self.user))
        if 'pricing' in self.fields:
            self.fields['pricing'].choices = get_duration_choices(self.user)

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

        # cat and sub_cat
        if self.user.profile.is_superuser:
            self.fields['sub_cat'].help_text = mark_safe(
                '<a href="{0}">{1}</a>'.format(
                    reverse('admin:directories_category_changelist'),
                    _('Manage Categories'),
                ))
        if self.instance and self.instance.pk:
            self.fields['sub_cat'].queryset = DirectoryCategory.objects.filter(
                parent=self.instance.cat)
        if args:
            post_data = args[0]
        else:
            post_data = None
        if post_data:
            cat = post_data.get('cat', '0')
            if cat and cat != '0' and cat != u'':
                cat = DirectoryCategory.objects.get(pk=int(cat))
                self.fields[
                    'sub_cat'].queryset = DirectoryCategory.objects.filter(
                        parent=cat)

        # 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 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 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 'pricing' in self.cleaned_data:
            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,
                    'creator': self.user,
                    'owner': self.user,
                })

            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
Пример #27
0
class ProjectForm(TendenciBaseForm):
    class Meta:
        model = Project
        fields = (
                'project_name',
                'slug',
                'project_number',
                'project_status',
                'category',
                'cost',
                'location',
                'city',
                'state',
                'project_manager',
                'project_description',
                'video_title',
                'video_description',
                'video_embed_code',
                'start_dt',
                'end_dt',
                'resolution',
                'client',
                'tags',
                'website_title',
                'website_url',
                'allow_anonymous_view',
                'user_perms',
                'group_perms',
                'member_perms',
                'status',
                'status_detail',
        )

    status_detail = forms.ChoiceField(choices=(('active','Active'),('pending','Pending')))
    project_description = forms.CharField(required=False,
        widget=TinyMCE(
            attrs={'style':'width:100%'},
            mce_attrs={
                'storme_app_label':u'projects',
                'storme_model':Project._meta.model_name.lower()
            }))
    video_description = forms.CharField(required=False,
        widget=TinyMCE(
            attrs={'style':'width:100%'},
            mce_attrs={
                'storme_app_label':u'projects',
                'storme_model':Project._meta.model_name.lower()
            }))
    resolution = forms.CharField(required=False,
        widget=TinyMCE(
            attrs={'style':'width:100%'},
            mce_attrs={
                'storme_app_label':u'projects',
                'storme_model':Project._meta.model_name.lower()
            }))

    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['project_description'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['video_description'].widget.mce_attrs['app_instance_id'] = self.instance.pk
            self.fields['resolution'].widget.mce_attrs['app_instance_id'] = self.instance.pk
        else:
            self.fields['project_description'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['video_description'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['resolution'].widget.mce_attrs['app_instance_id'] = 0
Пример #28
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 = forms.SplitDateTimeField(
        label=_('Release Date/Time'),
        input_date_formats=['%Y-%m-%d', '%m/%d/%Y'],
        input_time_formats=['%I:%M %p', '%H:%M:%S'])

    contributor_type = forms.ChoiceField(choices=CONTRIBUTOR_CHOICES,
                                         initial=Article.CONTRIBUTOR_AUTHOR,
                                         widget=forms.RadioSelect())
    thumbnail_file = forms.FileField(
        label=_('Thumbnail'),
        validators=[
            FileValidator(allowed_extensions=('.jpg', '.jpeg', '.gif', '.png'))
        ],
        required=False,
        help_text=_('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')),
    ))
    email = EmailVerificationField(label=_("Email"), required=False)
    group = forms.ChoiceField(required=True, choices=[])

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

        fieldsets = [(_('Article Information'), {
            'fields': [
                'headline',
                'slug',
                'summary',
                'body',
                'thumbnail_file',
                'group',
                'tags',
                'source',
                'website',
                'release_dt',
                'timezone',
            ],
            'legend':
            ''
        }),
                     (_('Contributor'), {
                         'fields': [
                             'contributor_type',
                         ],
                         '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.instance.thumbnail:
            self.initial['thumbnail_file'] = self.instance.thumbnail.file

        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['timezone'].initial = settings.TIME_ZONE

        self.fields['release_dt'].initial = datetime.now()

    def save(self, *args, **kwargs):
        article = super(ArticleForm, self).save(*args, **kwargs)

        content_type = ContentType.objects.get_for_model(Article)
        thumbnail_file = self.cleaned_data['thumbnail_file']

        if thumbnail_file:
            file_object, created = File.objects.get_or_create(
                file=thumbnail_file,
                defaults={
                    'name': thumbnail_file.name,
                    'content_type': content_type,
                    'object_id': article.pk,
                    'is_public': article.allow_anonymous_view,
                    'tags': article.tags,
                    'creator': self.user,
                    'owner': self.user,
                })

            article.thumbnail = file_object
            article.save(log=False)
        else:
            # clear thumbnail if box checked
            if article.thumbnail:
                article.thumbnail = None
                article.save(log=False)
                File.objects.filter(content_type=content_type,
                                    object_id=article.pk).delete()

        return article

    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
Пример #29
0
class CorpMembershipAppForm(TendenciBaseForm):
    description = forms.CharField(
        required=False,
        widget=TinyMCE(attrs={'style': 'width:70%'},
                       mce_attrs={
                           'storme_app_label':
                           CorpMembershipApp._meta.app_label,
                           'storme_model':
                           CorpMembershipApp._meta.model_name.lower()
                       }),
        help_text=_('Will show at the top of the application form.'))
    confirmation_text = forms.CharField(
        required=False,
        widget=TinyMCE(attrs={'style': 'width:70%'},
                       mce_attrs={
                           'storme_app_label':
                           CorpMembershipApp._meta.app_label,
                           'storme_model':
                           CorpMembershipApp._meta.model_name.lower()
                       }),
        help_text=_('Will show on the confirmation page.'))
    notes = forms.CharField(
        label=_('Notes'),
        required=False,
        widget=forms.Textarea(attrs={'rows': '3'}),
        help_text=_(
            'Notes for editor. Will not display on the application form.'))
    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('admin hold', _('Admin Hold')),
    ))

    class Meta:
        model = CorpMembershipApp
        fields = (
            'name',
            'slug',
            'corp_memb_type',
            'authentication_method',
            'memb_app',
            'payment_methods',
            'include_tax',
            'tax_rate',
            'description',
            'confirmation_text',
            'notes',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

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

    def clean(self):
        cleaned_data = super(CorpMembershipAppForm, self).clean()
        is_public = cleaned_data.get('allow_anonymous_view')
        corp_memb_types = cleaned_data.get('corp_memb_type')

        if is_public and corp_memb_types:
            public_types = [
                not cm_type.admin_only for cm_type in corp_memb_types
            ]
            if not any(public_types):
                raise forms.ValidationError(
                    _('Please select a public corporate membership type. \
                    All types currently selected are admin only.'))

        return cleaned_data
Пример #30
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