Merge branch 'master' into obrazy
authorMarcin Koziej <marcin@lolownia.org>
Sat, 7 Dec 2013 18:16:09 +0000 (19:16 +0100)
committerMarcin Koziej <marcin@lolownia.org>
Sat, 7 Dec 2013 18:16:09 +0000 (19:16 +0100)
1  2 
apps/catalogue/models/tag.py
apps/catalogue/urls.py
apps/catalogue/views.py

@@@ -2,6 -2,7 +2,7 @@@
  # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
  # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
  #
+ from django.conf import settings
  from django.contrib.auth.models import User
  from django.core.exceptions import ValidationError
  from django.db import models
@@@ -19,7 -20,6 +20,7 @@@ TAG_CATEGORIES = 
      ('theme', _('theme')),
      ('set', _('set')),
      ('book', _('book')),
 +    ('thing', _('thing')), # things shown on pictures
  )
  
  
@@@ -37,7 -37,6 +38,7 @@@ class Tag(TagBase)
  
      user = models.ForeignKey(User, blank=True, null=True)
      book_count = models.IntegerField(_('book count'), blank=True, null=True)
 +    picture_count = models.IntegerField(_('picture count'), blank=True, null=True)
      gazeta_link = models.CharField(blank=True, max_length=240)
      wiki_link = models.CharField(blank=True, max_length=240)
  
@@@ -54,7 -53,6 +55,7 @@@
          'gatunek': 'genre',
          'motyw': 'theme',
          'polka': 'set',
 +        'obiekt': 'thing',
      }
      categories_dict = dict((item[::-1] for item in categories_rev.iteritems()))
  
                      objects = objects.exclude(pk__in=descendants_keys)
          return objects.count()
  
 +    # I shouldn't break the get_count() api 
 +    # just to include pictures.
 +    def get_picture_count(self):
 +        from picture.models import Picture
 +        
 +        if self.category == 'book':
 +            # never used
 +            objects = Book.objects.none()
 +        elif self.category == 'theme':
 +            objects = Picture.tagged.with_all((self,))
 +        elif self.category == 'thing':
 +            objects = Picture.tagged.with_all((self,))
 +        else:
 +            objects = Picture.tagged.with_all((self,)).order_by()
 +        return objects.count()
 +        
      @staticmethod
      def get_tag_list(tags):
          if isinstance(tags, basestring):
                      # For instance, Pictures do not have 'genre' field.
                      continue
              for tag_name in tag_names:
+                 lang = getattr(tag_name, 'lang', settings.LANGUAGE_CODE)
                  tag_sort_key = tag_name
                  if category == 'author':
                      tag_sort_key = tag_name.last_name
                      tag_name = tag_name.readable()
-                 tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
-                 if created:
-                     tag.name = tag_name
-                     tag.sort_key = sortify(tag_sort_key.lower())
-                     tag.save()
-                 meta_tags.append(tag)
+                 if lang == settings.LANGUAGE_CODE:
+                     # Allow creating new tag, if it's in default language.
+                     tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
+                     if created:
+                         tag.name = tag_name
+                         setattr(tag, "name_%s" % lang, tag_name)
+                         tag.sort_key = sortify(tag_sort_key.lower())
+                         tag.save()
+                     meta_tags.append(tag)
+                 else:
+                     # Ignore unknown tags in non-default languages.
+                     try:
+                         tag = Tag.objects.get(category=category, **{"name_%s" % lang: tag_name})
+                     except Tag.DoesNotExist:
+                         pass
+                     else:
+                         meta_tags.append(tag)
          return meta_tags
diff --combined apps/catalogue/urls.py
@@@ -14,10 -14,8 +14,10 @@@ SLUG = r'[a-z0-9-]*
  
  urlpatterns = patterns('picture.views',
      # pictures - currently pictures are coupled with catalogue, hence the url is here
 -    url(r'^obraz/?$', 'picture_list'),
 -    url(r'^obraz/(?P<picture>%s)/?$' % SLUG, 'picture_detail')
 +    url(r'^obraz/?$', 'picture_list_thumb'),
 +    url(r'^obraz/(?P<slug>%s).html$' % SLUG, 'picture_viewer', name='picture_viewer'),
 +    url(r'^obraz/(?P<slug>%s)/?$' % SLUG, 'picture_detail'),
 +
  )
  
  urlpatterns += patterns('',
@@@ -34,7 -32,7 +34,7 @@@ urlpatterns += patterns('catalogue.view
      url(r'^audiobooki/$', 'audiobook_list', name='audiobook_list'),
      url(r'^daisy/$', 'daisy_list', name='daisy_list'),
      url(r'^tags/$', 'tags_starting_with', name='hint'),
-     url(r'^jtags/$', 'json_tags_starting_with', name='jhint'),
+     url(r'^jtags/?$', 'json_tags_starting_with', name='jhint'),
      url(r'^nowe/$', ListView.as_view(
          queryset=Book.objects.filter(parent=None).order_by('-created_at'),
          template_name='catalogue/recent_list.html'), name='recent_list'),
diff --combined apps/catalogue/views.py
@@@ -17,7 -17,7 +17,7 @@@ from django.contrib.auth.decorators imp
  from django.utils.datastructures import SortedDict
  from django.utils.http import urlquote_plus
  from django.utils import translation
- from django.utils.translation import ugettext as _, ugettext_lazy
+ from django.utils.translation import get_language, ugettext as _, ugettext_lazy
  from django.views.decorators.vary import vary_on_headers
  
  from ajaxable.utils import JSONResponse, AjaxableFormView
@@@ -29,7 -29,6 +29,7 @@@ from pdcounter import models as pdcount
  from pdcounter import views as pdcounter_views
  from suggest.forms import PublishingSuggestForm
  from picture.models import Picture
 +from picture.views import picture_list_thumb
  
  staff_required = user_passes_test(lambda user: user.is_staff)
  permanent_cache = get_cache('permanent')
  
  @vary_on_headers('X-Requested-With')
  def catalogue(request):
-     cache_key='catalogue.catalogue'
+     cache_key='catalogue.catalogue/' + get_language()
      output = permanent_cache.get(cache_key)
 +
      if output is None:
          tags = models.Tag.objects.exclude(
 -            category__in=('set', 'book')).exclude(book_count=0)
 +            category__in=('set', 'book')).exclude(book_count=0, picture_count=0)
          tags = list(tags)
          for tag in tags:
 -            tag.count = tag.book_count
 +            tag.count = tag.book_count + tag.picture_count
          categories = split_tags(tags)
          fragment_tags = categories.get('theme', [])
          collections = models.Collection.objects.all()
 +
          render_tag_list = lambda x: render_to_string(
              'catalogue/tag_list.html', tag_list(x))
 -        output = {'theme': render_tag_list(fragment_tags)}
 +        has_pictures = lambda x: filter(lambda y: y.picture_count>0, x)
 +        has_books = lambda x: filter(lambda y: y.book_count>0, x)
 +        def render_split(tags):
 +            with_books = has_books(tags)
 +            with_pictures = has_pictures(tags)
 +            ctx = {}
 +            if with_books:
 +                ctx['books'] = render_tag_list(with_books)
 +            if with_pictures:
 +                ctx['pictures'] = render_tag_list(with_pictures)
 +            return render_to_string('catalogue/tag_list_split.html', ctx)
 +
 +        output = {'theme': {}}
 +        output['theme'] = render_split(fragment_tags)
          for category, tags in categories.items():
 -            output[category] = render_tag_list(tags)
 +            output[category] = render_split(tags)
 +            
          output['collections'] = render_to_string(
              'catalogue/collection_list.html', collection_list(collections))
          permanent_cache.set(cache_key, output)
@@@ -87,6 -70,7 +87,7 @@@ def book_list(request, filter=None, get
          context=None,
          ):
      """ generates a listing of all books, optionally filtered with a test function """
+     cache_key = "%s/%s" % (cache_key, get_language())
      cached = permanent_cache.get(cache_key)
      if cached is not None:
          rendered_nav, rendered_book_list = cached
@@@ -120,16 -104,8 +121,16 @@@ def daisy_list(request)
  
  def collection(request, slug):
      coll = get_object_or_404(models.Collection, slug=slug)
 -    return book_list(request, get_filter=coll.get_query,
 -                     template_name='catalogue/collection.html',
 +    if coll.kind == 'book':
 +        view = book_list
 +        tmpl = "catalogue/collection.html"
 +    elif coll.kind == 'picture':
 +        view = picture_list_thumb
 +        tmpl = "picture/collection.html"
 +    else:
 +        raise ValueError('How do I show this kind of collection? %s' % coll.kind)
 +    return view(request, get_filter=coll.get_query,
 +                     template_name=tmpl,
                       cache_key='catalogue.collection:%s' % coll.slug,
                       context={'collection': coll})