I have created custom events plugin and now I want to display closest event on my home page (django-cms page with home.html template).
How can I do it? This is my event/models.py
from django.core.urlresolvers import reverse
from django.db import models
from adminsortable.models import Sortable
from easy_thumbnails.fields import ThumbnailerImageField
from cms.models.fields import PlaceholderField
from cms.models.pluginmodel import CMSPlugin
class Event(Sortable):
class Meta:
app_label = 'event'
event_name = models.CharField(
blank=False,
default='',
max_length=64,
)
date = models.DateField(
auto_now=False,
auto_now_add=False,
)
photo = ThumbnailerImageField(
upload_to='events',
blank=True,
)
def __unicode__(self):
return self.event_name
To get the latest event, you can override the render method of your plugin:
class YourCMSPlugIn(CMSPluginBase):
model = Event
...
def render(self, context, instance, placeholder):
context.update({
'latest_event': self.model.objects.all()[:1],
'placeholder': placeholder
})
return context
See: http://docs.django-cms.org/en/latest/extending_cms/custom_plugins.html#storing-configuration for more information.
Related
I'm implementing a newsletter app for a company website. My goal is to allow the 'future' website administrator to fire a newsletter directly from the admin.
For doing so, I wrote the following code:
models.py
from django.db import models
from ckeditor.fields import RichTextField
class NewsletterSubscription(models.Model):
datetime = models.DateTimeField(auto_now_add = True)
email = models.EmailField(max_length=128)
class Meta:
verbose_name = 'Iscritto Newsletter'
verbose_name_plural = 'Iscritti Newsletter'
def __unicode__(self):
return self.email
class Newsletter(models.Model):
EMAIL_STATUS_CHOICES = (
('Draft', 'Draft'),
('Pubblicata', 'Pubblicata')
)
subject = models.CharField(max_length=250)
body = RichTextField()
email = models.ManyToManyField(NewsletterSubscription)
status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.subject
I'd like to know if is possible to add to the NewsletterAdminForm a sort of button which allows to fire the email.
admin.py
from django import forms
from django.contrib import admin
from .models import NewsletterSubscription, Newsletter
from ckeditor.widgets import CKEditorWidget
class NewsletterSubscriptionAdmin(admin.ModelAdmin):
list_display = ('email', 'datetime', )
class NewsletterAdminForm(forms.ModelForm):
body = forms.CharField(widget=CKEditorWidget())
class Meta:
model = Newsletter
fields = '__all__'
class NewsletterAdmin(admin.ModelAdmin):
form = NewsletterAdminForm
admin.site.register(NewsletterSubscription, NewsletterSubscriptionAdmin)
admin.site.register(Newsletter, NewsletterAdmin)
Thank you in advance for any help you can provide.
To get a button in the admin panel you can simply create a method which will return the html:
class NewsletterAdmin(admin.ModelAdmin):
...
readonly_fields = ['send_mails']
def send_mails(self, obj):
url_red = 'url_of_your_view_to_send_mails'
return format_html(
'<a class="button" href="{}">Send</a> ',
url_red,
)
This will then get rendered as a button in the admin page which will send a GET request to the url supplied of the view, where you can define all the logic and send mails . Do include this custom field in the fields attribute.
Hope it helps.
I currently try to figure out how to implement the following:
https://github.com/danielquinn/django-encrypted-filefield
I only want to transparently encrypt my uploaded Data for later use on e.g. S3
First Problem is that I'm not able to get
from django.contrib.auth.mixins import AuthMixin
imported. I get the following exception:
from django.contrib.auth.mixins import AuthMixin
ImportError: cannot import name 'AuthMixin'
I'm simply not able to find it. At what package is it located?
and second is that I have no idea how to implement the view if I only want encrypt and decrypt the file on the fly.
Any suggestions?
my models.py
from django.db import models
from django.utils import timezone
from smartfields import fields
from smartfields.dependencies import FileDependency
from smartfields.processors import ImageProcessor
from django_encrypted_filefield.fields import EncryptedFileField
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField(max_length=10000)
tag = models.CharField(max_length=50, blank=True)
postattachment = EncryptedFileField(upload_to='postattachment/%Y/%m/%d/', blank=True, null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', blank=True, null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 300, 'max_height': 300}))
])
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
views.py
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'quickblog/post_detail.html', {'post': post})
Thank you :)
That mixin is not present in the django mixins. Maybe, the demo refers to a class extending any of the mixins you can find in django.
Having a look at the django sources, try with the class:
from django.contrib.auth.mixins import AccessMixin
In the view, try to show the encoded file, it must be stored already encrypted.
I am in process of creating Django CMS plugin. So far I have created a form, model and plugin file. I want to save SETTINGS info, but when I go to save it it gives error as mentioned above. Below are details.
cms_plugins.py
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models import CMSPlugin
from src.survey.forms import SurveyForm
from . import models
class SurveyPluginPublisher(CMSPluginBase):
"""Show Polls entered by Admin."""
cache = False
form = SurveyForm
model = models.SurveyPluginModel # Must add to show stuff.
module = "Survey"
name = "Awesome Survey v1.0"
render_template = 'survey/_hello.html'
plugin_pool.register_plugin(SurveyPluginPublisher)
forms.py
from django import forms
from src.survey.models import Survey
models.py
class SurveyForm(forms.Form):
# all_surveys = Survey.objects.only('name')
# surveys = forms.ModelChoiceField(queryset=all_surveys)
headline = forms.CharField(max_length=255, help_text='Enter Headline')
description = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}),help_text='Enter Description')
models.py
class SurveyPluginModel(CMSPlugin):
name = models.CharField("Survey Name", max_length=255, default='Survey Name',
help_text='Enter Survey Name')
description = models.CharField("Survey Description", max_length=500, blank=True, help_text='Write Description here')
def __str__(self):
return "Returning some Survey Text"
SurveyForm should be a subclass of ModelForm
class SurveyForm(forms.ModelForm):
class Meta:
model = SurveyPluginModel
The documentation for django-import-export is a bit weak on how to configure the admin to import from a spreadsheet. Does anyone have a full example?
This is not a fully complete module. But you can understand how it should be.
resources.py file
from import_export import resources
from .models import edxUser
class edxUserResource(resources.ModelResource):
class Meta:
model = edxUser
#skip_unchanged = True
#report_skipped = True
#if you want to exclude any field from exporting
exclude = ('id','edx_anonymized_id')
fields = ('id', 'edx_id', 'edx_anonymized_id', 'edx_email', 'edx_name', 'time_created', 'created_by')
#Order of the export fields
export_order = ('edx_id', 'edx_email')
admin.py file
from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .models import edxUser
from resources import edxUserResource
#admin.register(edxUser)
class edxUserAdmin(ImportExportModelAdmin):
resource_class = edxUserResource
models.py file
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
class edxUser(models.Model):
edx_id = models.IntegerField('edX user id', blank=True, null=True)
edx_anonymized_id = models.IntegerField("edX anonymized user id", blank=True, null=True)
edx_email = models.EmailField('edx user email', max_length=75, blank=True)
edx_name = models.CharField('edx name', max_length=75, blank=True, null=True)
time_created = models.DateField('Created time', blank=True, null=True)
created_by = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
def __unicode__(self):
return str(self.edx_id)
Here's how to do it, assuming that the column names in the spreadsheet are Title and Field one. This example assumes that the model instances will be created afresh every import (rather than being updated via a primary key).
from django.contrib import admin
from import_export.admin import ImportMixin
from import_export import resources, fields
from .models import MyModel
class MyModelResource(resources.ModelResource):
title = fields.Field(attribute='title',
column_name='Title')
field_one = fields.Field(attribute='field_one',
column_name='Field one')
def get_instance(self, instance_loader, row):
# Returning False prevents us from looking in the
# database for rows that already exist
return False
class Meta:
model = MyModel
fields = ('title', 'field_one')
export_order = fields
class MyModelAdmin(ImportMixin, admin.ModelAdmin):
resource_class = MyModelResource
admin.site.register(MyModel, MyModelAdmin)
i am new to django-rest-framework,i am unble to get the image as browse button in my rest framework,i am getting text field,here is my code as follows...........
views.py
from django.shortcuts import render
from serializers import *
from rest_framework import viewsets
class newsViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = news.objects.all()
serializer_class = newsSerializer
class news_categoriesViewSet(viewsets.ModelViewSet):
queryset = news_categories.objects.all()
serializer_class = news_categoriesSerializer
models.py
from django.db import models
from django.utils.encoding import smart_unicode
class news_categories(models.Model):
cat_name = models.CharField(max_length=30, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return smart_unicode(self.cat_name)
def Content_files(instance, filename):
return '/'.join(['Media','News Image', filename])
class news(models.Model):
name = models.CharField(max_length=30,null=True)
description = models.TextField()
cat_id = models.ForeignKey('news_categories')
image = models.FileField(upload_to=Content_files,null=True)
date = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return smart_unicode(self.name)
serializers.py
from django.forms import widgets
from rest_framework import serializers
from models import *
class newsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = news
fields = ('url','id','name','description','cat_id','image','date')
class news_categoriesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = news_categories
fields = ('url','id','cat_name')
Any one can Help me?Thanks in Advance....
the problem with settings.py and version of rest framework ,use 2.4.4
I stumbled upon the same problem when I updated to version 3.0. The solution is to define the FileField or ImageField in your serializer using a style attribute:
file = serializers.FileField(style = {'input_type': 'file'})