Example #1
0
class RegistrationChangeFormAdmin(forms.ModelForm):
    text = forms.CharField(widget=AdminTinyMCE(attrs={'cols': 80, 'rows': 30}),
                           label='')
    show_files = False
    show_preview = False

    class Meta:
        model = Registration
        fields = ('name','text','file', 'type_registration')

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

    def clean_file(self):
        uploaded_file = self.cleaned_data['file']
        error = clean_file(uploaded_file, image=True)
        if error:
            raise forms.ValidationError(error)
        return uploaded_file

    def save(self, commit=True):
        uploaded_file = super(RegistrationChangeFormAdmin, self).save(commit=False)
        uploaded_file.text = self.cleaned_data['text']
        if commit:
            uploaded_file.save()
        return uploaded_file
Example #2
0
class NewsChangeFormAdmin(forms.ModelForm):
    text = forms.CharField(widget=AdminTinyMCE(attrs={
        'cols': 80,
        'rows': 30
    }),
                           label='')
    show_files = True
    show_preview = True
    preview_url = "/preview_news/"

    class Meta:
        model = News
        fields = ('name', 'file')

    def __init__(self, *args, **kwargs):
        initial = {'text': self.text_initial}
        kwargs['initial'] = initial
        super(NewsChangeFormAdmin, self).__init__(*args, **kwargs)

    def clean_file(self):
        uploaded_file = self.cleaned_data['file']
        error = clean_file(uploaded_file, image=True)
        if error:
            raise forms.ValidationError(error)
        return uploaded_file

    def save(self, commit=True):
        uploaded_file = super(NewsChangeFormAdmin, self).save(commit=False)
        uploaded_file.text = self.cleaned_data['text']
        if commit:
            uploaded_file.save()
        return uploaded_file
Example #3
0
class NewsCreationFormAdmin(forms.ModelForm):
    text = forms.CharField(widget=AdminTinyMCE(attrs={
        'cols': 80,
        'rows': 30
    }),
                           label='')
    show_files = True
    show_preview = True
    preview_url = "/preview_news/"

    class Meta:
        model = News
        fields = ('name', 'file')

    def clean_file(self):
        uploaded_file = self.cleaned_data['file']
        error = clean_file(uploaded_file, image=True)
        if error:
            raise forms.ValidationError(error)
        return uploaded_file

    def save(self, commit=True):
        uploaded_file = super(NewsCreationFormAdmin, self).save(commit=False)
        uploaded_file.author = self.current_user
        uploaded_file.text = self.cleaned_data['text']
        if commit:
            uploaded_file.save()
        return uploaded_file
Example #4
0
 def formfield(self, **kwargs):
     defaults = {
         'widget': TinyMCE(profile=self.tinymce_profile)
     }
     defaults.update(kwargs)
     # As an ugly hack, we override the admin widget
     if defaults['widget'] == AdminTextareaWidget:
         defaults['widget'] = AdminTinyMCE(profile=self.tinymce_profile)
     return super(HTMLField, self).formfield(**defaults)
Example #5
0
class NewsPostAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.TextField: {
            'widget': AdminTinyMCE()
        },
    }
    list_display = ('title', 'body', 'user')
    readonly_fields = ('user', 'modified')

    def save_model(self, request, obj, form, change):
        obj.user = request.user
        obj.save()
Example #6
0
class ReviewAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',),}
    list_display = ['title', 'provider', 'author', 'source_id', 'slug', 'publish', 'complete', 'votes', 'reward', 'asset', 'btc', 'rub', 'get_out_link', ]
    formfield_overrides = {
        TextField: {'widget': AdminTinyMCE(attrs={'cols': 80, 'rows': 40}, )},
    }
    actions = [blockchain_publish_current_post_action, get_post_reward_action]

    def get_out_link(self, obj):
        return u"<a href='%s'>link</a>" % (obj.get_out_link())
    get_out_link.allow_tags = True
    get_out_link.short_description = 'profile'
Example #7
0
class SubjectPostChangeFormAdmin(forms.ModelForm):
    text = forms.CharField(widget=AdminTinyMCE(attrs={'cols': 80, 'rows': 30}),
                           label='')
    show_files = True
    show_preview = True
    preview_url = "/preview_subjectpost/"

    class Meta:
        model = SubjectPost
        fields = ('name', 'file', 'subject', 'subcategory')

    def __init__(self, *args, **kwargs):
        initial = {
            'text': self.text_initial
        }
        kwargs['initial'] = initial
        super(SubjectPostChangeFormAdmin, self).__init__(*args, **kwargs)
        user = self.current_user
        if user.status is 2:
            self.fields['subject'].queryset = user.subjects.all()

            self.fields['subcategory'].queryset = Subcategory.objects.filter(
                reduce(or_, [Q(subject=s) for s in user.subjects.all()]))

    def clean_file(self):
        uploaded_file = self.cleaned_data['file']
        error = clean_file(uploaded_file, image=True)
        if error:
            raise forms.ValidationError(error)
        return uploaded_file

    def clean_subject(self):
        subject = self.cleaned_data.get(
            "subject") if "subject" in self.changed_data else self.instance.subject
        subcategory = self.cleaned_data.get(
            "subcategory") if "subcategory" in self.changed_data else self.instance.subcategory
        if subcategory is not None and subject is not None and subject != subcategory.subject:
            raise forms.ValidationError(
                "This should be the same subject as the subcategory")
        if subcategory is None and subject is None:
            raise forms.ValidationError("This should not be empty")
        return self.cleaned_data.get("subject")

    def save(self, commit=True):
        post = super(SubjectPostChangeFormAdmin, self).save(commit=False)
        post.text = self.cleaned_data['text']
        post.subject = self.cleaned_data[
            "subject"] or self.cleaned_data["subcategory"].subject
        if commit:
            post.save()
        return post
Example #8
0
    def formfield_for_dbfield(self, db_field, **kwargs):
        """
        Enable TinyMCE for Text Fields

        :param db_field:
        :param kwargs:
        :return:
        """
        if db_field.name == 'content':
            kwargs.pop("request", None)
            kwargs['widget'] = AdminTinyMCE(attrs={'cols': 60, 'rows': 5})
            return db_field.formfield(**kwargs)

        return super(NewsEntryAdmin,
                     self).formfield_for_dbfield(db_field, **kwargs)
Example #9
0
 class Meta:
     model = Page
     fields = '__all__'
     widgets = {
         'meta_keywords': Textarea(attrs={
             'rows': 2,
             'cols': 100
         }),
         'meta_description': Textarea(attrs={'rows': 2}),
     }
     if hasattr(settings, 'CMS_WYSIWYG_EDITOR'):
         if settings.CMS_WYSIWYG_EDITOR == 'ckeditor':
             from ckeditor.widgets import CKEditorWidget
             widgets['content'] = CKEditorWidget()
         elif settings.CMS_WYSIWYG_EDITOR == 'tinymce':
             from tinymce.widgets import AdminTinyMCE
             widgets['content'] = AdminTinyMCE()
 class Meta:
     widgets = {
         'content':
         AdminTinyMCE(mce_attrs={
             'plugins':
             tinymce.settings.DEFAULT_CONFIG['plugins'] + ' | code',
             'toolbar':
             tinymce.settings.DEFAULT_CONFIG['toolbar'] + ' | code',
         }, )
     }
     fields = (
         'event',
         'name',
         'content',
         'background',
         'position',
         'is_public',
     )
Example #11
0
if settings.DBTEMPLATES_AUTO_POPULATE_CONTENT:
    content_help_text = _(
        "Leaving this empty causes Django to look for a "
        "template with the given name and populate this field with its "
        "content.")
else:
    content_help_text = ""

if settings.DBTEMPLATES_USE_CODEMIRROR and settings.DBTEMPLATES_USE_TINYMCE:
    raise ImproperlyConfigured(
        "You may use either CodeMirror or TinyMCE "
        "with dbtemplates, not both. Please disable one of them.")

if settings.DBTEMPLATES_USE_TINYMCE:
    from tinymce.widgets import AdminTinyMCE
    TemplateContentTextArea = AdminTinyMCE()

if settings.DBTEMPLATES_USE_CKEDITOR:
    from ckeditor.widgets import CKEditorWidget
    widget = CKEditorWidget()
    widget.config['entities'] = False
    TemplateContentTextArea = widget


class TemplateAdminForm(forms.ModelForm):
    """
    Custom AdminForm to make the content textarea wider.
    """
    content = forms.CharField(widget=TemplateContentTextArea,
                              help_text=content_help_text,
                              required=False)
Example #12
0
class OrganizationAdminForm(BaseOrganizationAdminForm):

    testimony = forms.CharField(widget=AdminTinyMCE(attrs={
        'cols': 80,
        'rows': 60
    }),
                                required=False)

    class Meta:
        model = get_model('coop_local', 'Organization')
        widgets = {
            'category': chosenwidgets.ChosenSelectMultiple(),
            'category_iae': chosenwidgets.ChosenSelectMultiple(),
            'guaranties': chosenwidgets.ChosenSelectMultiple(),
            'authors': chosenwidgets.ChosenSelectMultiple(),
            'activities': chosenwidgets.ChosenSelectMultiple(),
            'transverse_themes': forms.CheckboxSelectMultiple(),
        }

    def __init__(self, *args, **kwargs):

        # We do not call just super class, but super super class, because of redefinition of all parent logic
        super(OrganizationAdminForm, self).__init__(*args, **kwargs)
        self.fields['category_iae'].help_text = None

        engagements = self.instance.engagement_set.all()
        members_id = engagements.values_list('person_id', flat=True)
        org_contacts = Contact.objects.filter(
            Q(content_type=ContentType.objects.get(model='organization'),
              object_id=self.instance.id)
            | Q(content_type=ContentType.objects.get(model='person'),
                object_id__in=members_id))
        phone_categories = [1, 2]
        self.fields['pref_email'].queryset = org_contacts.filter(
            contact_medium_id=8)
        self.fields['pref_phone'].queryset = org_contacts.filter(
            contact_medium_id__in=phone_categories)
        self.fields['category'].help_text = None

        member_locations_id = [
            m.location.id for m in Person.objects.filter(
                id__in=members_id).exclude(location=None)
        ]  # limit SQL to location field

        self.fields['pref_address'].queryset = Location.objects.filter(
            Q(id__in=self.instance.located.all().values_list('location_id',
                                                             flat=True))
            | Q(id__in=member_locations_id))

        for field_name in ('workforce', 'production_workforce',
                           'supervision_workforce', 'integration_workforce',
                           'annual_integration_number'):
            self.fields[field_name].localize = True

    def clean_title(self):
        title = self.cleaned_data['title']
        norm_title = normalize_text(title)
        if Organization.objects.filter(norm_title=norm_title).exclude(
                pk=self.instance.pk).exists():
            raise forms.ValidationError(
                _('An organization with this title already exists.'))
        return title
Example #13
0
 class Meta:
     model = Post
     fields = "__all__"
     widgets = {"intro": AdminTextareaWidget(), "content": AdminTinyMCE()}
Example #14
0
class EventChangeFormAdmin(forms.ModelForm):
    date = forms.SplitDateTimeField()
    text = forms.CharField(widget=AdminTinyMCE(
        attrs={'cols': 80, 'rows': 30}), label='')
    address = forms.CharField(widget=map_widgets.GoogleMapsAddressWidget)
    geolocation = forms.CharField(widget=forms.HiddenInput(), label='')

    show_files = True
    show_preview = True
    preview_url = "/preview_event/"

    class Meta:
        model = Event
        fields = ('name', 'file')

    def __init__(self, *args, **kwargs):
        initial = {
            'text': self.text_initial,
            'date': self.date_initial,
            'address': self.address_initial,
            'geolocation': self.geolocation_initial,
        }
        kwargs['initial'] = initial
        super(EventChangeFormAdmin, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(EventChangeFormAdmin, self).clean()
        try:
            geoloc = cleaned_data['geolocation']
            addr = cleaned_data['address']
            if geoloc == "Invalid address or no results":
                cleaned_data['address'] = self.address_initial
                cleaned_data['geolocation'] = self.geolocation_initial
                self.add_error("address", forms.ValidationError(
                    "The address is invalid"))
            if addr == "Invalid geolocation":
                cleaned_data['address'] = self.address_initial
                cleaned_data['geolocation'] = self.geolocation_initial
                self.add_error("geolocation", forms.ValidationError(
                    "The geolocation is invalid"))
        except:
            cleaned_data['address'] = self.address_initial
            cleaned_data['geolocation'] = self.geolocation_initial
            self.add_error("address", forms.ValidationError(
                "The address is invalid"))
        return cleaned_data

    def clean_file(self):

        uploaded_file = self.cleaned_data['file']
        error = clean_file(uploaded_file, image=True)
        if error:
            raise forms.ValidationError(error)
        return uploaded_file

    def clean_date(self):
        data = self.cleaned_data['date']
        now = datetime.now()
        data = data.replace(tzinfo=None)
        if data < now:
            raise forms.ValidationError(
                "Data nu e valida.Nu puteti posta un eveniment in trecut!")
        return data

    def save(self, commit=True):
        uploaded_file = super(EventChangeFormAdmin, self).save(commit=False)
        uploaded_file.text = self.cleaned_data['text']
        uploaded_file.date = self.cleaned_data['date']
        uploaded_file.address = self.cleaned_data['address']
        uploaded_file.geolocation = self.cleaned_data['geolocation']
        if commit:
            uploaded_file.save()
        return uploaded_file