Vadim Chernysh avatar Vadim Chernysh committed 429035a

initial commit

Comments (0)

Files changed (27)

+syntax: glob
+*.orig
+*.pyc
+*.*~
+*_build*
+*.db
+whoosh
+media/uploads
+
+0.1
+
+Name: cmsplugin-advancednews
+Description: A advanced news plugin for django-cms based on cmsplugin-news
+Download: http://bitbucket.org/chernysh/cmsplugin-advancednews/
+
+Requirements:
+- django-cms-2.0.0 final
+- django: 1.1.1
++ requirements for django-cms-2.0
+
+Futures:
+- support categories for news. We can put to page all news or only from one category
+
+Setup:
+- make sure requirements are installed and properly working
+- add cmsplugin_advancednews to python path
+- add 'cmsplugin_advancednews' to INSTALLED_APPS
+- run 'python manage.py syncdb'
+- Add the cmsplugin_advancednews.urls to the CMS_APPLICATIONS_URLS setting 
+- Add the cmsplugin_advancednews.navigation.get_nodes to the CMS_NAVIGATION_EXTENDERS setting
+- Create a page in cms and in the 'advanced settings' section of the admin for that page, for 'Navigation extenders' select 'news navigation' and for 'application' select 'news' (Restart of the server required due to caching!)
+- Create the propper templates for your site, the ones included with the app are VERY basic
+
+Examples:
+
+CMS_APPLICATIONS_URLS = (
+    ('cmsplugin_advancednews.urls', 'News'),
+)
+CMS_NAVIGATION_EXTENDERS = (
+    ('cmsplugin_advancednews.navigation.get_nodes','News navigation'),
+)
+
+
+Todo:
+- support rss
Add a comment to this file

cmsplugin_advancednews/__init__.py

Empty file added.

cmsplugin_advancednews/admin.py

+from django.contrib import admin
+from django.utils.translation import ugettext_lazy as _
+from django.utils.translation import ungettext
+
+from cmsplugin_advancednews.forms import NewsForm
+from cmsplugin_advancednews.models import News, Category
+
+from multilingual.admin import MultilingualModelAdmin
+
+    
+class CategoryAdmin(MultilingualModelAdmin):
+    date_hierarchy = 'pub_date'
+    list_display = ('title', 'pub_date')    
+    
+class NewsAdmin(MultilingualModelAdmin):
+    """ Admin for news """
+
+    date_hierarchy = 'pub_date'
+    list_display = ('slug', 'title', 'category','is_published', 'pub_date')
+    list_filter = ('is_published', 'category',)
+    search_fields = ['title', 'excerpt', 'content']
+    form = NewsForm
+    
+    actions = ['make_published', 'make_unpublished']
+    
+    save_as = True
+    save_on_top = True
+
+    def queryset(self, request):
+        """ Override to use the objects and not just the default visibles only. """
+        return News.objects.all()
+       
+    def make_published(self, request, queryset):
+        """ Marks selected news items as published """
+        rows_updated = queryset.update(is_published=True)
+        self.message_user(request, ungettext('%(count)d newsitem was published', 
+                                             '%(count)d newsitems where published', 
+                                             rows_updated) % {'count': rows_updated})
+    make_published.short_description = _('Publish selected news')
+
+    def make_unpublished(self, request, queryset):
+        """ Marks selected news items as unpublished """
+        rows_updated =queryset.update(is_published=False)
+        self.message_user(request, ungettext('%(count)d newsitem was unpublished', 
+                                             '%(count)d newsitems where unpublished', 
+                                             rows_updated) % {'count': rows_updated})
+    make_unpublished.short_description = _('Unpublish selected news')
+
+admin.site.register(News, NewsAdmin)
+admin.site.register(Category, CategoryAdmin)

cmsplugin_advancednews/cms_app.py

+from cms.app_base import CMSApp
+from cms.apphook_pool import apphook_pool
+from django.utils.translation import ugettext_lazy as _
+
+class NewsApphook(CMSApp):
+    name = _("Latest Advanced News")
+    urls = ["cmsplugin_advancednews.urls"]
+
+apphook_pool.register(NewsApphook)

cmsplugin_advancednews/cms_plugins.py

+from django.utils.translation import ugettext_lazy as _
+
+from cms.plugin_base import CMSPluginBase
+from cms.plugin_pool import plugin_pool
+
+from cmsplugin_advancednews.models import LatestAdvancedNewsPlugin, News
+from cmsplugin_advancednews import settings
+
+from django.conf import settings
+
+class CMSLatestAdvancedNewsPlugin(CMSPluginBase):
+    """ Plugin class for the latest news """
+    model = LatestAdvancedNewsPlugin
+
+    name = _('Latest news')
+    render_template = 'cmsplugin_advancednews/latest_news.html'
+    
+    
+    def render(self, context, instance, placeholder):
+        """ Render the latest news """
+        query = News.published
+        if instance.category is None:
+            latest = query.all()[:instance.limit]
+        else:
+            latest = query.filter(category=instance.category).all()[:instance.limit]
+        context.update({
+            'instance': instance,
+            'latest': latest,
+            'placeholder': placeholder,
+        })
+        return context
+
+##if not settings.DISABLE_LATEST_ADVANCEDNEWS_PLUGIN:
+plugin_pool.register_plugin(CMSLatestAdvancedNewsPlugin)

cmsplugin_advancednews/forms.py

+from django import forms
+from django.conf import settings
+
+from cms.plugin_pool import plugin_pool
+from cms.plugins.text.settings import USE_TINYMCE
+from cmsplugin_advancednews.widgets.wymeditor_widget import WYMEditor
+
+from multilingual.admin import MultilingualModelAdminForm
+
+from cmsplugin_advancednews.models import News
+
+class NewsForm(MultilingualModelAdminForm):
+    class Meta:
+        model = News
+        
+    def _get_widget(self):
+        plugins = plugin_pool.get_text_enabled_plugins(placeholder=None, page=None)
+        if USE_TINYMCE and "tinymce" in settings.INSTALLED_APPS:
+            from cmsplugin_advancednews.widgets.tinymce_widget import TinyMCEEditor
+            return TinyMCEEditor(installed_plugins=plugins)
+        else:
+            return WYMEditor(installed_plugins=plugins)
+        
+        
+    def __init__(self, *args, **kwargs):
+        super(NewsForm, self).__init__(*args, **kwargs)
+        widget = self._get_widget()
+        self.fields['content'].widget = widget
+

cmsplugin_advancednews/migrations/0001_initial.py

+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Adding model 'NewsTranslation'
+        db.create_table('cmsplugin_advancednews_news_translation', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
+            ('excerpt', self.gf('django.db.models.fields.TextField')(blank=True)),
+            ('content', self.gf('django.db.models.fields.TextField')(blank=True)),
+            ('language_code', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=15, blank=True)),
+            ('master', self.gf('django.db.models.fields.related.ForeignKey')(related_name='translations', to=orm['cmsplugin_advancednews.News'])),
+        ))
+        db.send_create_signal('cmsplugin_advancednews', ['NewsTranslation'])
+
+        # Adding unique constraint on 'NewsTranslation', fields ['language_code', 'master']
+        db.create_unique('cmsplugin_advancednews_news_translation', ['language_code', 'master_id'])
+
+        # Adding model 'News'
+        db.create_table('cmsplugin_advancednews_news', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)),
+            ('category', self.gf('django.db.models.fields.related.ForeignKey')(default=None, related_name='n_category', null=True, blank=True, to=orm['cmsplugin_advancednews.Category'])),
+            ('is_published', self.gf('django.db.models.fields.BooleanField')(default=False)),
+            ('pub_date', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2010, 12, 20, 3, 19, 12, 359953))),
+            ('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
+            ('updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
+        ))
+        db.send_create_signal('cmsplugin_advancednews', ['News'])
+
+        # Adding model 'CategoryTranslation'
+        db.create_table('cmsplugin_advancednews_category_translation', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
+            ('language_code', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=15, blank=True)),
+            ('master', self.gf('django.db.models.fields.related.ForeignKey')(related_name='translations', to=orm['cmsplugin_advancednews.Category'])),
+        ))
+        db.send_create_signal('cmsplugin_advancednews', ['CategoryTranslation'])
+
+        # Adding unique constraint on 'CategoryTranslation', fields ['language_code', 'master']
+        db.create_unique('cmsplugin_advancednews_category_translation', ['language_code', 'master_id'])
+
+        # Adding model 'Category'
+        db.create_table('cmsplugin_advancednews_category', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('pub_date', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2010, 12, 20, 3, 19, 12, 364270))),
+            ('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
+            ('updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
+        ))
+        db.send_create_signal('cmsplugin_advancednews', ['Category'])
+
+        # Adding model 'LatestAdvancedNewsPlugin'
+        db.create_table('cmsplugin_latestadvancednewsplugin', (
+            ('cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
+            ('category', self.gf('django.db.models.fields.related.ForeignKey')(default=None, to=orm['cmsplugin_advancednews.Category'], null=True, blank=True)),
+            ('limit', self.gf('django.db.models.fields.PositiveIntegerField')()),
+        ))
+        db.send_create_signal('cmsplugin_advancednews', ['LatestAdvancedNewsPlugin'])
+
+
+    def backwards(self, orm):
+        
+        # Removing unique constraint on 'CategoryTranslation', fields ['language_code', 'master']
+        db.delete_unique('cmsplugin_advancednews_category_translation', ['language_code', 'master_id'])
+
+        # Removing unique constraint on 'NewsTranslation', fields ['language_code', 'master']
+        db.delete_unique('cmsplugin_advancednews_news_translation', ['language_code', 'master_id'])
+
+        # Deleting model 'NewsTranslation'
+        db.delete_table('cmsplugin_advancednews_news_translation')
+
+        # Deleting model 'News'
+        db.delete_table('cmsplugin_advancednews_news')
+
+        # Deleting model 'CategoryTranslation'
+        db.delete_table('cmsplugin_advancednews_category_translation')
+
+        # Deleting model 'Category'
+        db.delete_table('cmsplugin_advancednews_category')
+
+        # Deleting model 'LatestAdvancedNewsPlugin'
+        db.delete_table('cmsplugin_latestadvancednewsplugin')
+
+
+    models = {
+        'cms.cmsplugin': {
+            'Meta': {'object_name': 'CMSPlugin'},
+            'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
+            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
+            'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
+            'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
+            'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
+            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
+        },
+        'cms.placeholder': {
+            'Meta': {'object_name': 'Placeholder'},
+            'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
+        },
+        'cmsplugin_advancednews.category': {
+            'Meta': {'ordering': "('-pub_date',)", 'object_name': 'Category'},
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'pub_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2010, 12, 20, 3, 19, 12, 364270)'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
+        },
+        'cmsplugin_advancednews.categorytranslation': {
+            'Meta': {'ordering': "('language_code',)", 'unique_together': "(('language_code', 'master'),)", 'object_name': 'CategoryTranslation', 'db_table': "'cmsplugin_advancednews_category_translation'"},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'language_code': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '15', 'blank': 'True'}),
+            'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'translations'", 'to': "orm['cmsplugin_advancednews.Category']"}),
+            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'cmsplugin_advancednews.latestadvancednewsplugin': {
+            'Meta': {'object_name': 'LatestAdvancedNewsPlugin', 'db_table': "'cmsplugin_latestadvancednewsplugin'", '_ormbases': ['cms.CMSPlugin']},
+            'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['cmsplugin_advancednews.Category']", 'null': 'True', 'blank': 'True'}),
+            'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
+            'limit': ('django.db.models.fields.PositiveIntegerField', [], {})
+        },
+        'cmsplugin_advancednews.news': {
+            'Meta': {'ordering': "('-pub_date',)", 'object_name': 'News'},
+            'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'n_category'", 'null': 'True', 'blank': 'True', 'to': "orm['cmsplugin_advancednews.Category']"}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'pub_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2010, 12, 20, 3, 19, 12, 359953)'}),
+            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
+        },
+        'cmsplugin_advancednews.newstranslation': {
+            'Meta': {'ordering': "('language_code',)", 'unique_together': "(('language_code', 'master'),)", 'object_name': 'NewsTranslation', 'db_table': "'cmsplugin_advancednews_news_translation'"},
+            'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
+            'excerpt': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'language_code': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '15', 'blank': 'True'}),
+            'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'translations'", 'to': "orm['cmsplugin_advancednews.News']"}),
+            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        }
+    }
+
+    complete_apps = ['cmsplugin_advancednews']
Add a comment to this file

cmsplugin_advancednews/migrations/__init__.py

Empty file added.

cmsplugin_advancednews/models.py

+import datetime
+
+from django.db import models
+from django.utils.translation import ugettext_lazy as _
+
+from cms.models import CMSPlugin
+
+from multilingual.translation import TranslationModel
+from multilingual.exceptions import TranslationDoesNotExist
+from multilingual.manager import MultilingualManager
+
+
+class PublishedNewsManager(models.Manager):
+    """ Filters out all unpublished and items with a publication date in the future. """
+
+    def get_query_set(self):
+        return super(PublishedNewsManager, self).get_query_set().filter(is_published=True).filter(pub_date__lte=datetime.datetime.now())
+
+    
+class News(models.Model):
+    """ News model """
+    
+    slug = models.SlugField(_('Slug'), unique_for_date='pub_date', 
+                            help_text=_('A slug is a short name which uniquely identifies the news item for this day'))
+
+    category = models.ForeignKey("Category", related_name="n_category",
+                        null=True, blank=True, default=None)
+
+    is_published = models.BooleanField(_('Published'), default=False)
+    pub_date = models.DateTimeField(_('Publication date'), default=datetime.datetime.now())
+    
+    created = models.DateTimeField(auto_now_add=True, editable=False)
+    updated = models.DateTimeField(auto_now=True, editable=False)
+    
+    published = PublishedNewsManager()
+    objects = MultilingualManager()
+    
+    class Meta:
+        verbose_name = _('News')
+        verbose_name_plural = _('News')
+        ordering = ('-pub_date', )
+
+    class Translation(TranslationModel):
+        title = models.CharField(_('Title'), max_length=255)
+        excerpt = models.TextField(_('Excerpt'), blank=True)
+        content = models.TextField(_('Content'), blank=True)
+        
+    def __unicode__(self):
+        try:
+            return u'%s'% (self.title)
+        except TranslationDoesNotExist:
+            return u'-not-available-'
+
+    @models.permalink
+    def get_absolute_url(self):
+        return ('news_detail', (), {
+            'year': self.pub_date.strftime("%Y"),
+            'month': self.pub_date.strftime("%m"),
+            'day': self.pub_date.strftime("%d"),
+            'slug': self.slug,
+            })
+
+class Category(models.Model):
+    """
+    Category
+    """
+    
+    pub_date        = models.DateTimeField(_('Publication date'), default=datetime.datetime.now())
+    created         = models.DateTimeField(auto_now_add=True, editable=False)
+    updated         = models.DateTimeField(auto_now=True, editable=False)
+    
+    class Meta:
+        verbose_name = _('Category')
+        verbose_name_plural = _('Categories')
+        ordering = ('-pub_date', )
+    
+    
+    class Translation(TranslationModel):
+        title = models.CharField(_('Title'), max_length=255)
+
+    def __unicode__(self):
+        try:
+            return u'%s'% (self.title)
+        except TranslationDoesNotExist:
+            return u'-not-available-'
+
+
+class LatestAdvancedNewsPlugin(CMSPlugin):
+    """ Model for the settings when using the latest news cms plugin. """
+    
+    category = models.ForeignKey(Category, null=True, blank=True, default=None)
+    limit = models.PositiveIntegerField(_('Number of news items to show'), 
+                                        help_text=_('Limits the number of items that will be displayed'))

cmsplugin_advancednews/navigation.py

+from datetime import datetime
+from django.core.urlresolvers import reverse
+
+from menus.base import NavigationNode
+from cmsplugin_news.models import News
+
+def get_nodes(request):
+    res = []
+    
+    items = News.published.all()
+    
+    years_done = []
+    months_done = []
+    days_done = []
+    slug_done = []
+    
+    for item in items:
+        date = item.pub_date
+        
+        if not date.year in years_done:
+            years_done.append(date.year)
+            year_node = NavigationNode(date.year, reverse('news_archive_year', kwargs=dict(year=date.year)))
+            year_node.childrens = []
+            months_done = []
+            res.append(year_node)
+        
+        if not date.month in months_done:
+            months_done.append(date.month)
+            month_node = NavigationNode(datetime.strftime(date, '%B'), 
+                                        reverse('news_archive_month', kwargs=dict(
+                                            year=date.year, 
+                                            month=datetime.strftime(date, '%m'))))
+            month_node.childrens = []
+            days_done = []
+            year_node.childrens.append(month_node)
+            
+        if not date.day in days_done:
+            days_done.append(date.day)
+            day_node = NavigationNode(datetime.strftime(date, '%d'), 
+                                      reverse('news_archive_day', kwargs=dict(
+                                          year=date.year, 
+                                          month=datetime.strftime(date, '%m'),
+                                          day=datetime.strftime(date, '%d'))))
+            day_node.childrens = []
+            slug_done = []
+            month_node.childrens.append(day_node)
+            
+        if not item.slug in slug_done:
+            slug_done.append(item.slug)
+            item_node = NavigationNode(item.title, item.get_absolute_url())
+            item_node.childrens = []
+            day_node.childrens.append(item_node)
+            
+    return res

cmsplugin_advancednews/settings.py

+from django.conf import settings as django_settings
+
+# Uses CKEditor as editor (no inline plugins). Requires ckeditor app. 
+USE_CKEDITOR = getattr(django_settings, 'CMS_USE_CKEDITOR', "ckeditor" in django_settings.INSTALLED_APPS)
+
+DISABLE_LATEST_NEWS_PLUGIN = getattr(django_settings, 'CMSPLUGIN_NEWS_DISABLE_LATEST_NEWS_PLUGIN', False)

cmsplugin_advancednews/templates/cmsplugin_advancednews/latest_news.html

+{% load i18n %}
+
+<h1>{% trans "Latest news" %}</h1>
+<ul>
+  {% for news in latest %}
+    <li><a href="{{ news.get_absolute_url }}">{{ news.title }}</a></li>
+  {% empty %}
+    <li>{% trans "No news yet" %}</li>
+  {% endfor %}
+</ul>
+<a href="{% url news_archive_index %}">{% trans "Archive" %}</a>

cmsplugin_advancednews/templates/cmsplugin_advancednews/news_archive.html

+{% load i18n %}
+
+<h1>{% trans "Latest news" %}</h1>
+
+{% for object in latest %}
+  <p><strong>{{ object.title }}</strong><br/><a href="{{ object.get_absolute_url }}">{% trans "Read more" %}</a></p>
+{% endfor %}

cmsplugin_advancednews/templates/cmsplugin_advancednews/news_archive_day.html

+{% load i18n %}
+
+<h1>{% blocktrans %}News for {{ day }}{% endblocktrans %}</h1>
+
+<ul>
+  {% for object in object_list %}
+    <li><a href="{{ object.get_absolute_url }}">{{ object.title }}</a></li>
+  {% empty %}
+    <li>{% trans "No news for this day"</li>
+  {% endfor %}
+</ul>

cmsplugin_advancednews/templates/cmsplugin_advancednews/news_archive_month.html

+{% load i18n %}
+
+<h1>{% blocktrans %}News for {{ month }}{% endblocktrans %}</h1>
+
+<ul>
+  {% for object in object_list %}
+    <li><a href="{{ object.get_absolute_url }}">{{ object.title }}</a></li>
+  {% empty %}
+    <li>{% trans "No news for this month" %}</li>
+  {% endfor %}
+</ul>

cmsplugin_advancednews/templates/cmsplugin_advancednews/news_archive_year.html

+{% load i18n %}
+
+<h1>{% blocktrans %}News for {{ year }}{% endblocktrans %}</h1>
+<ul>
+  {% for date in date_list %}
+    <li><a href="{% url news_archive_month year=year month=date|date:'m'  %}">{{ date|date:"F" }}</a></li>
+  {% empty %}
+    <li>{% trans "No news for this year" %}</li>
+  {% endfor %}
+</ul>

cmsplugin_advancednews/templates/cmsplugin_advancednews/news_detail.html

+<h1>{{ object.title }}</h1>
+
+<p><span class="date">{{ object.pub_date }}</span><br/>
+  {{ object.content|safe }}
+</p>
+

cmsplugin_advancednews/templates/cmsplugin_advancednews/widgets/tinymce.html

+{% load i18n %}
+
+// Global var, for storing callbacks, see below.
+var editPluginPopupCallbacks = {};
+
+{% include "cms/plugins/widgets/widget_lib.js" %}

cmsplugin_advancednews/templates/cmsplugin_advancednews/widgets/wymeditor.html

+{% load i18n %}
+<script type="text/javascript">
+
+// Global var, for storing callbacks, see below.
+var editPluginPopupCallbacks = {};
+
+{% include "cms/plugins/widgets/widget_lib.js" %}
+
+
+
+$(document).ready(function(){
+    $('#id_{{ name }}').wymeditor({
+        lang: '{{ language }}',
+        skin: 'django',
+        skinPath: "{{ CMS_MEDIA_URL }}js/wymeditor/skins/django/",
+        updateSelector: 'input[type=submit],',
+        updateEvent: 'click',
+		logoHtml: '',
+		toolsItems: [
+			    {{ WYM_TOOLS }}
+			],
+		containersItems: [
+		        {{ WYM_CONTAINERS }}
+		    ],
+		classesItems: [
+			    {{ WYM_CLASSES }}
+			],
+		editorStyles: [
+			{{ WYM_STYLES }}
+			],
+		{% if WYM_STYLESHEET %}
+		stylesheet:
+			{{ WYM_STYLESHEET }}
+		,
+		{% endif %}
+        //handle click event on dialog's submit button
+        postInitDialog: function( wym, wdw ) {
+     
+        }
+    });
+});
+    </script>

cmsplugin_advancednews/tests.py

+"""
+Tests for the cmsplugin_news app
+"""
+
+import datetime
+
+from django.test import TestCase
+
+from cmsplugin_advancednews.models import News
+from cmsplugin_advancednews.navigation import get_nodes
+
+class NewsTest(TestCase):
+    def setUp(self):
+        self.today = datetime.datetime.today()
+        self.yesterday = self.today - datetime.timedelta(days=1)
+        self.tomorrow = self.today + datetime.timedelta(days=1)
+        
+    def tearDown(self):
+        pass
+
+        
+    def test_unpublished(self):
+        """
+            Test if unpublished items are hidden by default
+        """
+        unpublished = News.objects.create(
+            title='Unpublished News',
+            slug='unpublished-news',
+            is_published=False,
+            pub_date=self.yesterday,
+        )
+        self.assertEquals(News.published.count(), 0)
+        unpublished.is_published = True
+        unpublished.save()
+        self.assertEquals(News.published.count(), 1)
+        unpublished.is_published = False
+        unpublished.save()
+        self.assertEquals(News.published.count(), 0)
+        
+        unpublished.delete()
+        
+    def test_future_published(self):
+        """
+            Tests that items with a future published date are hidden
+        """
+        future_published = News.objects.create(
+            title='Future published News',
+            slug='future-published-news',
+            is_published=True,
+            pub_date=self.tomorrow,
+        )
+        self.assertEquals(News.published.count(), 0)
+        future_published.pub_date = self.yesterday
+        future_published.save()
+        self.assertEquals(News.published.count(), 1)
+        future_published.pub_date = self.tomorrow
+        future_published.save()
+        self.assertEquals(News.published.count(), 0)
+        
+    def test_navigation(self):
+        """
+            Tests if the navigation build by navigation.get_nodes is correct
+        """
+        pass

cmsplugin_advancednews/urls.py

+from django.conf.urls.defaults import *
+
+from cmsplugin_advancednews.models import News
+
+news_info_dict = {
+    'queryset': News.published.all(),
+    'date_field': 'pub_date',
+}
+
+news_info_month_dict = {
+    'queryset': News.published.all(),
+    'date_field': 'pub_date',
+    'month_format': '%m',
+}
+
+urlpatterns = patterns('django.views.generic.date_based',
+                       (r'^$',
+                        'archive_index', news_info_dict, 'news_archive_index'),
+
+                       (r'^(?P<year>\d{4})/$',
+                        'archive_year', news_info_dict, 'news_archive_year'),
+
+                       (r'^(?P<year>\d{4})/(?P<month>\d{2})/$',
+                        'archive_month', news_info_month_dict, 'news_archive_month'),
+
+                       (r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$',
+                        'archive_day', news_info_month_dict, 'news_archive_day'),
+
+                       (r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
+                        'object_detail', news_info_month_dict, 'news_detail'),
+                       )
+

cmsplugin_advancednews/views.py

+# Create your views here.
Add a comment to this file

cmsplugin_advancednews/widgets/__init__.py

Empty file added.

cmsplugin_advancednews/widgets/tinymce_widget.py

+from tinymce.widgets import TinyMCE, get_language_config
+from django.conf import settings
+from django.utils.translation import get_language
+from django.template.loader import render_to_string
+from django.utils.safestring import mark_safe
+from os.path import join
+from django.utils.encoding import smart_unicode
+import tinymce.settings
+from django.utils import simplejson
+from django.template.defaultfilters import escape
+from django.forms.widgets import flatatt
+import cms.plugins.text.settings
+
+class TinyMCEEditor(TinyMCE):
+    
+    def __init__(self, installed_plugins=None,  **kwargs):
+        super(TinyMCEEditor, self).__init__(**kwargs)
+        self.installed_plugins = installed_plugins
+        
+    def render_additions(self, name, value, attrs=None):
+        language = get_language()
+        context = {
+            'name': name,
+            'language': language,
+            'CMS_MEDIA_URL': settings.CMS_MEDIA_URL,
+            'installed_plugins': self.installed_plugins,
+        }
+        return mark_safe(render_to_string(
+            'cmsplugin_advancednews/widgets/tinymce.html', context))
+        
+    def _media(self):
+        media = super(TinyMCEEditor, self)._media()
+        media.add_js([join(settings.CMS_MEDIA_URL, path) for path in (
+                      'js/lib/jquery.js',
+                      )])
+        media.add_css({"all":[join(settings.CMS_MEDIA_URL, path) for path in ('css/jquery/cupertino/jquery-ui.css',
+                                                                     'css/tinymce_toolbar.css')]})
+        
+        return media
+    
+    
+    media = property(_media)
+    
+    def render(self, name, value, attrs=None):
+        if value is None: value = ''
+        value = smart_unicode(value)
+        final_attrs = self.build_attrs(attrs)
+        final_attrs['name'] = name
+        assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'"
+        mce_config = cms.plugins.text.settings.TINYMCE_CONFIG.copy()
+        mce_config.update(get_language_config(self.content_language))
+        if tinymce.settings.USE_FILEBROWSER:
+            mce_config['file_browser_callback'] = "djangoFileBrowser"
+        mce_config.update(self.mce_attrs)
+        mce_config['mode'] = 'exact'
+        mce_config['elements'] = final_attrs['id']
+        mce_config['strict_loading_mode'] = 1
+        """
+        plugins = mce_config.get("plugins", "")
+        if len(plugins):
+            plugins += ","
+        plugins += "-cmsplugins"
+        mce_config['plugins'] = plugins
+        adv2 = mce_config.get('theme_advanced_buttons1', "")
+        if len(adv2):
+            adv2 = "," + adv2
+        adv2 = "cmsplugins,cmspluginsedit" + adv2
+        mce_config['theme_advanced_buttons1'] = adv2
+        """
+        json = simplejson.dumps(mce_config)
+        
+        html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))]
+        if tinymce.settings.USE_COMPRESSOR:
+            compressor_config = {
+                'plugins': mce_config.get('plugins', ''),
+                'themes': mce_config.get('theme', 'advanced'),
+                'languages': mce_config.get('language', ''),
+                'diskcache': True,
+                'debug': False,
+            }
+            c_json = simplejson.dumps(compressor_config)
+            html.append(u'<script type="text/javascript">tinyMCE_GZ.init(%s);</script>' % (c_json))
+        html.append(u'<script type="text/javascript">%s;\ntinyMCE.init(%s);</script>' % (self.render_additions(name, value, attrs), json))
+        return mark_safe(u'\n'.join(html))
+    
+    
+    

cmsplugin_advancednews/widgets/wymeditor_widget.py

+from os.path import join
+
+from django.utils.safestring import mark_safe
+from django.template.loader import render_to_string
+from django.forms import Textarea
+
+from django.conf import settings
+from cms.plugins.text import settings as text_settings
+from django.utils.translation.trans_real import get_language
+
+class WYMEditor(Textarea):
+    class Media:
+        js = [join(settings.CMS_MEDIA_URL, path) for path in (
+            'js/lib/jquery.js',
+            'wymeditor/jquery.wymeditor.js',
+            'wymeditor/plugins/resizable/jquery.wymeditor.resizable.js',
+        )]
+              
+    def __init__(self, attrs=None, installed_plugins=None):
+        """
+        Create a widget for editing text + plugins.
+
+        installed_plugins is a list of plugins to display that are text_enabled
+        """
+        self.attrs = {'class': 'wymeditor'}
+        if attrs:
+            self.attrs.update(attrs)
+        super(WYMEditor, self).__init__(attrs)
+        self.installed_plugins = installed_plugins
+        
+    def render_textarea(self, name, value, attrs=None):
+        return super(WYMEditor, self).render(name, value, attrs)
+
+    def render_additions(self, name, value, attrs=None):
+        language = get_language()
+        context = {
+            'name': name,
+            'language': language,
+            'CMS_MEDIA_URL': settings.CMS_MEDIA_URL,
+            'WYM_TOOLS': mark_safe(text_settings.WYM_TOOLS),
+            'WYM_CONTAINERS': mark_safe(text_settings.WYM_CONTAINERS),
+            'WYM_CLASSES': mark_safe(text_settings.WYM_CLASSES),
+            'WYM_STYLES': mark_safe(text_settings.WYM_STYLES),
+            'WYM_STYLESHEET': mark_safe(text_settings.WYM_STYLESHEET),
+            'installed_plugins': self.installed_plugins,
+        }
+        return mark_safe(render_to_string(
+            'cmsplugin_advancednews/widgets/wymeditor.html', context))
+
+    def render(self, name, value, attrs=None):
+        return self.render_textarea(name, value, attrs) + \
+            self.render_additions(name, value, attrs)
+from setuptools import setup, find_packages
+
+setup(
+    name='cmsplugin-advancednews',
+    version='0.1',
+    description='This is a news app/plugin for the django-cms 2',
+    author='Vadim Chernysh',
+    author_email='chernysh.vadim@gmail.com',
+    url='http://bitbucket.org/chernysh/cmsplugin-advancednews/',
+    packages=find_packages(),
+    classifiers=[
+        'Development Status :: 4 - Beta',
+        'Environment :: Web Environment',
+        'Intended Audience :: Developers',
+        'License :: OSI Approved :: BSD License',
+        'Operating System :: OS Independent',
+        'Programming Language :: Python',
+        'Framework :: Django',
+    ],
+    include_package_data=True,
+    zip_safe=False,
+    install_requires=['setuptools', 'setuptools_bzr'],
+)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.