Skip to content

Commit

Permalink
Merge pull request #93 from glogiotatidis/admin_update
Browse files Browse the repository at this point in the history
Admin update
  • Loading branch information
glogiotatidis committed Feb 2, 2015
2 parents 79eaa9a + d593dc5 commit b798029
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 6 deletions.
29 changes: 26 additions & 3 deletions snippets/base/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import re

from django.contrib import admin
Expand Down Expand Up @@ -52,6 +53,15 @@ def cmr_to_locales_action(modeladmin, request, queryset):
'to Locale Rules')



@transaction.commit_on_success
def duplicate_snippets_action(modeladmin, request, queryset):
for snippet in queryset:
snippet.duplicate()
duplicate_snippets_action.short_description = 'Duplicate selected snippets'



class TemplateNameFilter(admin.AllValuesFieldListFilter):
def __init__(self, *args, **kwargs):
super(TemplateNameFilter, self).__init__(*args, **kwargs)
Expand All @@ -67,8 +77,10 @@ class BaseSnippetAdmin(BaseModelAdmin):

list_display = (
'name',
'priority',
'id',
'disabled',
'text',
'locales',
'publish_start',
'publish_end',
'modified',
Expand All @@ -84,7 +96,6 @@ class BaseSnippetAdmin(BaseModelAdmin):
)
list_editable = (
'disabled',
'priority',
'publish_start',
'publish_end'
)
Expand All @@ -94,6 +105,7 @@ class BaseSnippetAdmin(BaseModelAdmin):
save_as = True

filter_horizontal = ('client_match_rules',)
actions = (duplicate_snippets_action,)

def save_model(self, request, obj, form, change):
"""Save locale changes as well as the snippet itself."""
Expand All @@ -113,6 +125,9 @@ def change_view(self, request, *args, **kwargs):
request.POST['disabled'] = u'on'
return super(BaseSnippetAdmin, self).change_view(request, *args, **kwargs)

def locales(self, obj):
return ', '.join([locale.get_locale_display() for locale in obj.locale_set.all()])


class SnippetAdmin(BaseSnippetAdmin):
form = forms.SnippetAdminForm
Expand Down Expand Up @@ -164,7 +179,7 @@ class SnippetAdmin(BaseSnippetAdmin):
}),
)

actions = (cmr_to_locales_action,)
actions = (cmr_to_locales_action, duplicate_snippets_action)

class Media:
css = {
Expand All @@ -176,6 +191,14 @@ def lookup_allowed(self, key, value):
return True
return super(SnippetAdmin, self).lookup_allowed(key, value)

def text(self, obj):
text = []
data = json.loads(obj.data)
text_keys = (obj.template.variable_set
.filter(type=models.SnippetTemplateVariable.TEXT)
.values_list('name', flat=True))
return '\n'.join([data[key] for key in text_keys if data[key]])


class ClientMatchRuleAdmin(BaseModelAdmin):
list_display = ('description', 'is_exclusion', 'startpage_version', 'name',
Expand Down
36 changes: 34 additions & 2 deletions snippets/base/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import copy
import hashlib
import json
import os
Expand All @@ -6,6 +7,7 @@
import xml.sax
from StringIO import StringIO
from collections import namedtuple
from datetime import datetime
from urlparse import urljoin
from xml.sax import ContentHandler

Expand All @@ -15,6 +17,7 @@
from django.core.files.base import ContentFile
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.manager import Manager
from django.template.loader import render_to_string

import jingo
Expand Down Expand Up @@ -156,6 +159,7 @@ def generate(self):
cache.set(self.cache_key, True, settings.SNIPPET_BUNDLE_TIMEOUT)



class SnippetTemplate(CachingMixin, models.Model):
"""
A template for the body of a snippet. Can have multiple variables that the
Expand Down Expand Up @@ -258,7 +262,35 @@ def __unicode__(self):
return self.description


class Snippet(CachingMixin, models.Model):
class SnippetBaseModel(models.Model):
def duplicate(self):
snippet_copy = copy.copy(self)
snippet_copy.id = None
snippet_copy.disabled = True
snippet_copy.name = '{0} - {1}'.format(
self.name,
datetime.strftime(datetime.now(), '%Y.%m.%d %H:%M:%S'))
snippet_copy.save()

for field in self._meta.get_all_field_names():
if isinstance(getattr(self, field), Manager):
manager = getattr(self, field)
if manager.__class__.__name__ == 'RelatedManager':
for itm in manager.all():
itm_copy = copy.copy(itm)
itm_copy.id = None
getattr(snippet_copy, field).add(itm_copy)
elif manager.__class__.__name__ == 'ManyRelatedManager':
for snippet in manager.all():
getattr(snippet_copy, field).add(snippet)

return snippet_copy

class Meta:
abstract = True


class Snippet(CachingMixin, SnippetBaseModel):
name = models.CharField(max_length=255, unique=True)
template = models.ForeignKey(SnippetTemplate)
data = models.TextField(default='{}', validators=[validate_xml])
Expand Down Expand Up @@ -359,7 +391,7 @@ class SnippetLocale(CachingMixin, models.Model):
cached_objects = CachingManager()


class JSONSnippet(CachingMixin, models.Model):
class JSONSnippet(CachingMixin, SnippetBaseModel):
name = models.CharField(max_length=255, unique=True)
priority = models.IntegerField(default=0, blank=True)
disabled = models.BooleanField(default=True)
Expand Down
19 changes: 19 additions & 0 deletions snippets/base/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,32 @@

from snippets.base.models import Client, SnippetBundle, UploadedFile, validate_xml
from snippets.base.tests import (ClientMatchRuleFactory,
JSONSnippetFactory,
SearchProviderFactory,
SnippetFactory,
SnippetTemplateFactory,
SnippetTemplateVariableFactory,
TestCase,
UploadedFileFactory)

class DuplicateSnippetMixInTests(TestCase):
def _dup_test(self, snippet):
snippet.client_match_rules.add(*ClientMatchRuleFactory.create_batch(3))
snippet_copy = snippet.duplicate()
eq_(snippet_copy.disabled, True)
ok_(snippet_copy.id != snippet.id)
eq_(snippet_copy.locale_set.count(), 1)
ok_(snippet_copy.locale_set.all()[0] != snippet.locale_set.all()[0])
eq_(set(snippet_copy.client_match_rules.all()), set(snippet.client_match_rules.all()))

def test_snippet(self):
snippet = SnippetFactory.create()
self._dup_test(snippet)

def test_json_snippet(self):
snippet = JSONSnippetFactory.create()
self._dup_test(snippet)


class ClientMatchRuleTests(TestCase):
def _client(self, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion vendor
Submodule vendor updated 3579 files

0 comments on commit b798029

Please sign in to comment.