Remove legacy code

This commit is contained in:
Iacopo Spalletti 2016-06-06 00:08:28 +02:00
parent 238980a16b
commit 1f2b42fdb7
No known key found for this signature in database
GPG Key ID: BDCBC2EB289F60C6
8 changed files with 63 additions and 280 deletions

View File

@ -77,6 +77,7 @@ HELPER_SETTINGS = dict(
CMS_TEMPLATES=(
('blog.html', 'Blog template'),
),
META_USE_SITES=True,
META_SITE_PROTOCOL='http',
META_SITE_DOMAIN='example.com',
META_USE_OG_PROPERTIES=True,

View File

@ -7,7 +7,7 @@ from django.utils.translation import ugettext_lazy as _
from djangocms_apphook_setup.base import AutoCMSAppMixin
from .cms_appconfig import BlogConfig
from .menu import BlogCategoryMenu
from .cms_menus import BlogCategoryMenu
from .settings import get_setting

View File

@ -3,6 +3,7 @@ from __future__ import absolute_import, print_function, unicode_literals
from cms.apphook_pool import apphook_pool
from cms.menu_bases import CMSAttachMenu
from django.contrib.sites.shortcuts import get_current_site
from django.core.urlresolvers import resolve
from django.db.models.signals import post_delete, post_save
from django.utils.translation import get_language_from_request, ugettext_lazy as _
@ -13,11 +14,6 @@ from .cms_appconfig import BlogConfig
from .models import BlogCategory, Post
from .settings import MENU_TYPE_CATEGORIES, MENU_TYPE_COMPLETE, MENU_TYPE_POSTS, get_setting
try:
from django.contrib.sites.shortcuts import get_current_site
except ImportError:
from django.contrib.sites.models import get_current_site
class BlogCategoryMenu(CMSAttachMenu):
"""

View File

@ -4,71 +4,69 @@ from __future__ import absolute_import, print_function, unicode_literals
import warnings
from cms.utils.permissions import get_current_user
from cms.wizards.wizard_base import Wizard
from cms.wizards.wizard_pool import AlreadyRegisteredException, wizard_pool
from django import forms
from django.conf import settings
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from parler.forms import TranslatableModelForm
try:
from cms.wizards.wizard_base import Wizard
from cms.wizards.wizard_pool import wizard_pool, AlreadyRegisteredException
from parler.forms import TranslatableModelForm
from .cms_appconfig import BlogConfig
from .models import Post
from .cms_appconfig import BlogConfig
from .models import Post
class PostWizardForm(TranslatableModelForm):
default_appconfig = None
class PostWizardForm(TranslatableModelForm):
default_appconfig = None
def __init__(self, *args, **kwargs):
if 'initial' not in kwargs or not kwargs.get('initial', False):
kwargs['initial'] = {}
kwargs['initial']['app_config'] = self.default_appconfig
if 'data' in kwargs and kwargs['data'] is not None:
kwargs['data']['1-app_config'] = self.default_appconfig
super(PostWizardForm, self).__init__(*args, **kwargs)
self.fields['app_config'].widget = forms.Select(
attrs=self.fields['app_config'].widget.attrs,
choices=self.fields['app_config'].widget.choices,
)
self.fields['app_config'].widget.attrs['disabled'] = True
class Meta:
model = Post
fields = ['app_config', 'title', 'abstract', 'categories']
class Media:
js = ('admin/js/jquery.js', 'admin/js/jquery.init.js',)
def save(self, commit=True):
self.instance._set_default_author(get_current_user())
return super(PostWizardForm, self).save(commit)
class PostWizard(Wizard):
pass
for config in BlogConfig.objects.all().order_by('namespace'):
seed = slugify('{0}.{1}'.format(config.app_title, config.namespace))
new_wizard = type(str(seed), (PostWizard,), {})
new_form = type(str('{0}Form').format(seed), (PostWizardForm,), {
'default_appconfig': config.pk
})
post_wizard = new_wizard(
title=_('New {0}').format(config.object_name),
weight=200,
form=new_form,
model=Post,
description=_('Create a new {0} in {1}').format(config.object_name, config.app_title),
def __init__(self, *args, **kwargs):
if 'initial' not in kwargs or not kwargs.get('initial', False):
kwargs['initial'] = {}
kwargs['initial']['app_config'] = self.default_appconfig
if 'data' in kwargs and kwargs['data'] is not None:
kwargs['data']['1-app_config'] = self.default_appconfig
super(PostWizardForm, self).__init__(*args, **kwargs)
self.fields['app_config'].widget = forms.Select(
attrs=self.fields['app_config'].widget.attrs,
choices=self.fields['app_config'].widget.choices,
)
try:
wizard_pool.register(post_wizard)
except AlreadyRegisteredException: # pragma: no cover
if settings.DEBUG:
raise
else:
warnings.warn('Wizard {0} cannot be registered. Please make sure that '
'BlogConfig.namespace {1} and BlogConfig.app_title {2} are'
'unique together'.format(seed, config.namespace, config.app_title))
except ImportError:
# For django CMS version not supporting wizards just ignore this file
self.fields['app_config'].widget.attrs['disabled'] = True
class Meta:
model = Post
fields = ['app_config', 'title', 'abstract', 'categories']
class Media:
js = ('admin/js/jquery.js', 'admin/js/jquery.init.js',)
def save(self, commit=True):
self.instance._set_default_author(get_current_user())
return super(PostWizardForm, self).save(commit)
class PostWizard(Wizard):
pass
for config in BlogConfig.objects.all().order_by('namespace'):
seed = slugify('{0}.{1}'.format(config.app_title, config.namespace))
new_wizard = type(str(seed), (PostWizard,), {})
new_form = type(str('{0}Form').format(seed), (PostWizardForm,), {
'default_appconfig': config.pk
})
post_wizard = new_wizard(
title=_('New {0}').format(config.object_name),
weight=200,
form=new_form,
model=Post,
description=_('Create a new {0} in {1}').format(config.object_name, config.app_title),
)
try:
wizard_pool.register(post_wizard)
except AlreadyRegisteredException: # pragma: no cover
if settings.DEBUG:
raise
else:
warnings.warn('Wizard {0} cannot be registered. Please make sure that '
'BlogConfig.namespace {1} and BlogConfig.app_title {2} are'
'unique together'.format(seed, config.namespace, config.app_title))

View File

@ -1,189 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from heapq import nlargest
from itertools import ifilter, repeat
from operator import itemgetter
class Counter(dict):
"""
Dict subclass for counting hashable objects. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
>>> Counter('zyzygy')
Counter({'y': 3, 'z': 2, 'g': 1})
"""
def __init__(self, iterable=None, **kwds):
"""
Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
"""
self.update(iterable, **kwds)
def __missing__(self, key):
return 0
def most_common(self, n=None):
"""List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
"""
if n is None:
return sorted(self.iteritems(), key=itemgetter(1), reverse=True)
return nlargest(n, self.iteritems(), key=itemgetter(1))
def elements(self):
"""Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it.
"""
for elem, count in self.iteritems():
for _ in repeat(None, count):
yield elem
# Override dict methods where the meaning changes for Counter objects.
@classmethod
def fromkeys(cls, iterable, v=None):
raise NotImplementedError(
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
def update(self, iterable=None, **kwds):
"""Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d) # add elements from another counter
>>> c['h'] # four 'h' in which, witch, and watch
4
"""
if iterable is not None:
if hasattr(iterable, 'iteritems'):
if self:
self_get = self.get
for elem, count in iterable.iteritems():
self[elem] = self_get(elem, 0) + count
else:
dict.update(self, iterable) # fast path when counter is empty
else:
self_get = self.get
for elem in iterable:
self[elem] = self_get(elem, 0) + 1
if kwds:
self.update(kwds)
def copy(self):
'Like dict.copy() but returns a Counter instance instead of a dict.'
return Counter(self)
def __delitem__(self, elem):
'Like dict.__delitem__() but does not raise KeyError for missing values.'
if elem in self:
dict.__delitem__(self, elem)
def __repr__(self):
if not self:
return '%s()' % self.__class__.__name__
items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
return '%s({%s})' % (self.__class__.__name__, items)
# Multiset-style mathematical operations discussed in:
# Knuth TAOCP Volume II section 4.6.3 exercise 19
# and at http://en.wikipedia.org/wiki/Multiset
#
# Outputs guaranteed to only include positive counts.
#
# To strip negative and zero counts, add-in an empty counter:
# c += Counter()
def __add__(self, other):
"""Add counts from two counters.
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
"""
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem in set(self) | set(other):
newcount = self[elem] + other[elem]
if newcount > 0:
result[elem] = newcount
return result
def __sub__(self, other):
""" Subtract count, but keep only results with positive counts.
>>> Counter('abbbc') - Counter('bccd')
Counter({'b': 2, 'a': 1})
"""
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem in set(self) | set(other):
newcount = self[elem] - other[elem]
if newcount > 0:
result[elem] = newcount
return result
def __or__(self, other):
"""Union is the maximum of value in either of the input counters.
>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})
"""
if not isinstance(other, Counter):
return NotImplemented
_max = max
result = Counter()
for elem in set(self) | set(other):
newcount = _max(self[elem], other[elem])
if newcount > 0:
result[elem] = newcount
return result
def __and__(self, other):
""" Intersection is the minimum of corresponding counts.
>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
"""
if not isinstance(other, Counter):
return NotImplemented
_min = min
result = Counter()
if len(self) < len(other):
self, other = other, self
for elem in ifilter(self.__contains__, other):
newcount = _min(self[elem], other[elem])
if newcount > 0:
result[elem] = newcount
return result

View File

@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import django
from collections import Counter
from aldryn_apphooks_config.managers.parler import (
AppHookConfigTranslatableManager, AppHookConfigTranslatableQueryset,
)
@ -9,11 +10,6 @@ from django.contrib.sites.models import Site
from django.db import models
from django.utils.timezone import now
try:
from collections import Counter
except ImportError:
from .compat import Counter
class TaggedFilterItem(object):
@ -129,12 +125,7 @@ class GenericDateTaggedManager(TaggedFilterItem, AppHookConfigTranslatableManage
queryset_class = GenericDateQuerySet
def get_queryset(self, *args, **kwargs):
try:
return super(GenericDateTaggedManager, self).get_queryset(*args, **kwargs)
except AttributeError: # pragma: no cover
return super(GenericDateTaggedManager, self).get_query_set(*args, **kwargs)
if django.VERSION < (1, 8):
get_query_set = get_queryset
return super(GenericDateTaggedManager, self).get_queryset(*args, **kwargs)
def published(self):
return self.get_queryset().published()

View File

@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
from djangocms_blog.cms_menus import * # NOQA

View File

@ -2,17 +2,9 @@
from __future__ import absolute_import, print_function, unicode_literals
import sys
from distutils.version import LooseVersion
import cms
from .base import BaseTest
try:
from unittest import skipIf
except ImportError:
from unittest2 import skipIf
class WizardTest(BaseTest):
@ -32,8 +24,6 @@ class WizardTest(BaseTest):
pass
super(WizardTest, self).setUp()
@skipIf(LooseVersion(cms.__version__) < LooseVersion('3.2'),
reason='Wizards not available for django CMS < 3.2')
def test_wizard(self):
"""
Test that Blog wizard is present and contains all items
@ -45,8 +35,6 @@ class WizardTest(BaseTest):
self.assertTrue('New Blog' in titles)
self.assertTrue('New Article' in titles)
@skipIf(LooseVersion(cms.__version__) < LooseVersion('3.2'),
reason='Wizards not available for django CMS < 3.2')
def test_wizard_init(self):
from cms.utils.permissions import current_user
from cms.wizards.wizard_pool import wizard_pool
@ -88,4 +76,4 @@ class WizardTest(BaseTest):
def test_wizard_import(self):
# The following import should not fail in any django CMS version
from djangocms_blog import cms_wizards # NOQA
pass