refactoring: replaced locals() by explicit dicts
authorJan Szejko <j-sz@o2.pl>
Tue, 2 Feb 2016 14:53:13 +0000 (15:53 +0100)
committerJan Szejko <j-sz@o2.pl>
Tue, 2 Feb 2016 14:53:13 +0000 (15:53 +0100)
src/api/management/commands/mobileinit.py
src/catalogue/templates/catalogue/book_wide.html
src/catalogue/templatetags/catalogue_tags.py
src/catalogue/views.py
src/infopages/views.py
src/pdcounter/views.py
src/picture/templates/picture/picture_wide.html
src/picture/views.py
src/reporting/views.py
src/social/views.py
src/waiter/views.py

index b89fede..ed4d624 100755 (executable)
@@ -97,7 +97,7 @@ CREATE TABLE state (last_checked INTEGER);
 """
 
     db.executescript(schema)
 """
 
     db.executescript(schema)
-    db.execute("INSERT INTO state VALUES (:last_checked)", locals())
+    db.execute("INSERT INTO state VALUES (:last_checked)", {'last_checked': last_checked})
     return db
 
 
     return db
 
 
@@ -133,29 +133,30 @@ categories = {'author': 'autor',
 
 
 def add_book(db, book):
 
 
 def add_book(db, book):
-    title = book.title
     if book.html_file:
         html_file = book.html_file.url
         html_file_size = book.html_file.size
     else:
         html_file = html_file_size = None
     if book.html_file:
         html_file = book.html_file.url
         html_file_size = book.html_file.size
     else:
         html_file = html_file_size = None
-    if book.cover:
-        cover = book.cover.url
-    else:
-        cover = None
-    parent = book.parent_id
-    parent_number = book.parent_number
-    sort_key = book.sort_key
-    size_str = pretty_size(html_file_size)
-    authors = ", ".join(t.name for t in book.tags.filter(category='author'))
-    db.execute(book_sql, locals())
+    db.execute(book_sql, {
+        'title': book.title,
+        'cover': book.cover.url if book.cover else None,
+        'html_file': html_file,
+        'html_file_size': html_file_size,
+        'parent': book.parent_id,
+        'parent_number': book.parent_number,
+        'sort_key': book.sort_key,
+        'size_str': pretty_size(html_file_size),
+        'authors': ", ".join(t.name for t in book.tags.filter(category='author')),
+    })
 
 
 def add_tag(db, tag):
 
 
 def add_tag(db, tag):
-    category = categories[tag.category]
-    name = tag.name
-    sort_key = tag.sort_key
-
     books = Book.tagged_top_level([tag])
     books = Book.tagged_top_level([tag])
-    book_ids = ','.join(str(b.id) for b in books)
-    db.execute(tag_sql, locals())
+    book_ids = ','.join(str(book_id) for book_id in books.values_list('id', flat=True))
+    db.execute(tag_sql, {
+        'category': categories[tag.category],
+        'name': tag.name,
+        'sort_key': tag.sort_key,
+        'book_ids': book_ids,
+    })
index 26ee55d..aa78292 100644 (file)
@@ -1,6 +1,6 @@
 {% extends "catalogue/book_short.html" %}
 {% load i18n %}
 {% extends "catalogue/book_short.html" %}
 {% load i18n %}
-{% load choose_fragment download_audio tag_list custom_pdf_link_li license_icon source_name from catalogue_tags %}
+{% load choose_fragment download_audio custom_pdf_link_li license_icon source_name from catalogue_tags %}
 {% load choose_cite from social_tags %}
 {% load ssi_include from ssify %}
 
 {% load choose_cite from social_tags %}
 {% load ssi_include from ssify %}
 
index 23eeeda..16d5de7 100644 (file)
@@ -306,9 +306,9 @@ class CatalogueURLNode(Node):
             return reverse('book_list')
 
 
             return reverse('book_list')
 
 
-@register.inclusion_tag('catalogue/tag_list.html')
+@register.inclusion_tag('catalogue/tag_list.html')
 def tag_list(tags, choices=None, category=None, gallery=False):
 def tag_list(tags, choices=None, category=None, gallery=False):
-    print(tags, choices, category)
+    print(tags, choices, category)
     if choices is None:
         choices = []
 
     if choices is None:
         choices = []
 
@@ -319,6 +319,8 @@ def tag_list(tags, choices=None, category=None, gallery=False):
 
     if len(tags) == 1 and category not in [t.category for t in choices]:
         one_tag = tags[0]
 
     if len(tags) == 1 and category not in [t.category for t in choices]:
         one_tag = tags[0]
+    else:
+        one_tag = None
 
     if category is not None:
         other = Tag.objects.filter(category=category).exclude(pk__in=[t.pk for t in tags])\
 
     if category is not None:
         other = Tag.objects.filter(category=category).exclude(pk__in=[t.pk for t in tags])\
@@ -326,8 +328,15 @@ def tag_list(tags, choices=None, category=None, gallery=False):
         # Filter out empty tags.
         ct = ContentType.objects.get_for_model(Picture if gallery else Book)
         other = other.filter(items__content_type=ct).distinct()
         # Filter out empty tags.
         ct = ContentType.objects.get_for_model(Picture if gallery else Book)
         other = other.filter(items__content_type=ct).distinct()
+    else:
+        other = []
 
 
-    return locals()
+    return {
+        'one_tag': one_tag,
+        'choices': choices,
+        'tags': tags,
+        'other': other,
+    }
 
 
 @register.inclusion_tag('catalogue/inline_tag_list.html')
 
 
 @register.inclusion_tag('catalogue/inline_tag_list.html')
@@ -337,7 +346,7 @@ def inline_tag_list(tags, choices=None, category=None, gallery=False):
 
 @register.inclusion_tag('catalogue/collection_list.html')
 def collection_list(collections):
 
 @register.inclusion_tag('catalogue/collection_list.html')
 def collection_list(collections):
-    return locals()
+    return {'collections': collections}
 
 
 @register.inclusion_tag('catalogue/book_info.html')
 
 
 @register.inclusion_tag('catalogue/book_info.html')
@@ -351,7 +360,7 @@ def book_info(book):
 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
 def work_list(context, object_list):
     request = context.get('request')
 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
 def work_list(context, object_list):
     request = context.get('request')
-    return locals()
+    return {'object_list': object_list, 'request': request}
 
 
 @register.inclusion_tag('catalogue/plain_list.html', takes_context=True)
 
 
 @register.inclusion_tag('catalogue/plain_list.html', takes_context=True)
@@ -372,7 +381,14 @@ def plain_list(context, object_list, with_initials=True, by_author=False, choice
                 last_initial = initial
                 names.append((obj.author_str() if by_author else initial, []))
         names[-1][1].append(obj)
                 last_initial = initial
                 names.append((obj.author_str() if by_author else initial, []))
         names[-1][1].append(obj)
-    return locals()
+    return {
+        'paged': paged,
+        'names': names,
+        'initial_blocks': initial_blocks,
+        'book': book,
+        'gallery': gallery,
+        'choice': choice,
+    }
 
 
 # TODO: These are no longer just books.
 
 
 # TODO: These are no longer just books.
index 09f48c7..271e796 100644 (file)
@@ -33,11 +33,12 @@ from catalogue.utils import split_tags
 staff_required = user_passes_test(lambda user: user.is_staff)
 
 
 staff_required = user_passes_test(lambda user: user.is_staff)
 
 
-def catalogue(request, as_json=False):
-    books = models.Book.objects.filter(parent=None).order_by('sort_key_author', 'sort_key')
-    pictures = Picture.objects.order_by('sort_key_author', 'sort_key')
-    collections = models.Collection.objects.all()
-    return render(request, 'catalogue/catalogue.html', locals())
+def catalogue(request):
+    return render(request, 'catalogue/catalogue.html', {
+        'books': models.Book.objects.filter(parent=None).order_by('sort_key_author', 'sort_key'),
+        'pictures': Picture.objects.order_by('sort_key_author', 'sort_key'),
+        'collections': models.Collection.objects.all(),
+    })
 
 
 def book_list(request, filter=None, get_filter=None, template_name='catalogue/book_list.html',
 
 
 def book_list(request, filter=None, get_filter=None, template_name='catalogue/book_list.html',
@@ -51,9 +52,15 @@ def book_list(request, filter=None, get_filter=None, template_name='catalogue/bo
     for tag in books_by_author:
         if books_by_author[tag]:
             books_nav.setdefault(tag.sort_key[0], []).append(tag)
     for tag in books_by_author:
         if books_by_author[tag]:
             books_nav.setdefault(tag.sort_key[0], []).append(tag)
-    rendered_nav = render_to_string(nav_template_name, locals())
-    rendered_book_list = render_to_string(list_template_name, locals())
-    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
+    # WTF: dlaczego nie include?
+    return render_to_response(template_name, {
+        'rendered_nav': render_to_string(nav_template_name, {'books_nav': books_nav}),
+        'rendered_book_list': render_to_string(list_template_name, {
+            'books_by_author': books_by_author,
+            'orphans': orphans,
+            'books_by_parent': books_by_parent,
+        })
+    }, context_instance=RequestContext(request))
 
 
 def audiobook_list(request):
 
 
 def audiobook_list(request):
@@ -239,7 +246,11 @@ def book_fragments(request, slug, theme_slug):
     fragments = models.Fragment.tagged.with_all([theme]).filter(
         Q(book=book) | Q(book__ancestor=book))
 
     fragments = models.Fragment.tagged.with_all([theme]).filter(
         Q(book=book) | Q(book__ancestor=book))
 
-    return render_to_response('catalogue/book_fragments.html', locals(), context_instance=RequestContext(request))
+    return render_to_response('catalogue/book_fragments.html', {
+        'book': book,
+        'theme': theme,
+        'fragments': fragments,
+    }, context_instance=RequestContext(request))
 
 
 def book_detail(request, slug):
 
 
 def book_detail(request, slug):
@@ -248,9 +259,11 @@ def book_detail(request, slug):
     except models.Book.DoesNotExist:
         return pdcounter_views.book_stub_detail(request, slug)
 
     except models.Book.DoesNotExist:
         return pdcounter_views.book_stub_detail(request, slug)
 
-    tags = book.tags.exclude(category__in=('set', 'theme'))
-    book_children = book.children.all().order_by('parent_number', 'sort_key')
-    return render_to_response('catalogue/book_detail.html', locals(), context_instance=RequestContext(request))
+    return render_to_response('catalogue/book_detail.html', {
+        'book': book,
+        'tags': book.tags.exclude(category__in=('set', 'theme')),
+        'book_children': book.children.all().order_by('parent_number', 'sort_key'),
+    }, context_instance=RequestContext(request))
 
 
 def get_audiobooks(book):
 
 
 def get_audiobooks(book):
@@ -284,6 +297,7 @@ def get_audiobooks(book):
     return audiobooks, projects, have_oggs
 
 
     return audiobooks, projects, have_oggs
 
 
+# używane tylko do audiobook_tree, które jest używane tylko w snippets/audiobook_list.html, które nie jest używane
 def player(request, slug):
     book = get_object_or_404(models.Book, slug=slug)
     if not book.has_media('mp3'):
 def player(request, slug):
     book = get_object_or_404(models.Book, slug=slug)
     if not book.has_media('mp3'):
@@ -291,9 +305,14 @@ def player(request, slug):
 
     audiobooks, projects, have_oggs = get_audiobooks(book)
 
 
     audiobooks, projects, have_oggs = get_audiobooks(book)
 
-    extra_info = book.extra_info
+    extra_info = book.extra_info
 
 
-    return render_to_response('catalogue/player.html', locals(), context_instance=RequestContext(request))
+    return render_to_response('catalogue/player.html', {
+        'book': book,
+        'audiobook': '',
+        'audiobooks': audiobooks,
+        'projects': projects,
+    }, context_instance=RequestContext(request))
 
 
 def book_text(request, slug):
 
 
 def book_text(request, slug):
@@ -301,7 +320,7 @@ def book_text(request, slug):
 
     if not book.has_html_file():
         raise Http404
 
     if not book.has_html_file():
         raise Http404
-    return render_to_response('catalogue/book_text.html', locals(), context_instance=RequestContext(request))
+    return render_to_response('catalogue/book_text.html', {'book': book,}, context_instance=RequestContext(request))
 
 
 # ==========
 
 
 # ==========
@@ -561,7 +580,7 @@ def book_info(request, book_id, lang='pl'):
     book = get_object_or_404(models.Book, id=book_id)
     # set language by hand
     translation.activate(lang)
     book = get_object_or_404(models.Book, id=book_id)
     # set language by hand
     translation.activate(lang)
-    return render_to_response('catalogue/book_info.html', locals(), context_instance=RequestContext(request))
+    return render_to_response('catalogue/book_info.html', {'book': book}, context_instance=RequestContext(request))
 
 
 def tag_info(request, tag_id):
 
 
 def tag_info(request, tag_id):
index 443fbda..4d1731f 100644 (file)
@@ -19,6 +19,10 @@ def infopage(request, slug):
     try:
         right_column = Template(page.right_column).render(rc)
     except TemplateSyntaxError:
     try:
         right_column = Template(page.right_column).render(rc)
     except TemplateSyntaxError:
-        left_column = ''
+        right_column = ''
 
 
-    return render_to_response('infopages/infopage.html', locals(), context_instance=RequestContext(request))
+    return render_to_response('infopages/infopage.html', {
+        'page': page,
+        'left_column': left_column,
+        'right_columns': right_column,
+    }, context_instance=RequestContext(request))
index eee6bfc..b8a685e 100644 (file)
@@ -15,10 +15,16 @@ def book_stub_detail(request, slug):
     book = get_object_or_404(models.BookStub, slug=slug)
     if book.pd and not book.in_pd():
         pd_counter = datetime(book.pd, 1, 1)
     book = get_object_or_404(models.BookStub, slug=slug)
     if book.pd and not book.in_pd():
         pd_counter = datetime(book.pd, 1, 1)
+    else:
+        pd_counter = None
 
     form = PublishingSuggestForm(initial={"books": u"%s — %s, \n" % (book.author, book.title)})
 
 
     form = PublishingSuggestForm(initial={"books": u"%s — %s, \n" % (book.author, book.title)})
 
-    return render_to_response('pdcounter/book_stub_detail.html', locals(), context_instance=RequestContext(request))
+    return render_to_response('pdcounter/book_stub_detail.html', {
+        'book': book,
+        'pd_counter': pd_counter,
+        'form': form,
+    }, context_instance=RequestContext(request))
 
 
 @cache.never_cache
 
 
 @cache.never_cache
@@ -26,7 +32,13 @@ def author_detail(request, slug):
     author = get_object_or_404(models.Author, slug=slug)
     if not author.alive():
         pd_counter = datetime(author.goes_to_pd(), 1, 1)
     author = get_object_or_404(models.Author, slug=slug)
     if not author.alive():
         pd_counter = datetime(author.goes_to_pd(), 1, 1)
+    else:
+        pd_counter = None
 
     form = PublishingSuggestForm(initial={"books": author.name + ", \n"})
 
 
     form = PublishingSuggestForm(initial={"books": author.name + ", \n"})
 
-    return render_to_response('pdcounter/author_detail.html', locals(), context_instance=RequestContext(request))
+    return render_to_response('pdcounter/author_detail.html', {
+        'author': author,
+        'pd_counter': pd_counter,
+        'form': form,
+    }, context_instance=RequestContext(request))
index 462e8b0..00260f5 100644 (file)
   <div class="other-tools">
     <h2 class="mono">{% trans "See" %}</h2>
     <ul class="plain">
   <div class="other-tools">
     <h2 class="mono">{% trans "See" %}</h2>
     <ul class="plain">
-      {% if extra_info.source_url %}
-      <li><a href="{{ extra_info.source_url }}">{% trans "Source" %}</a> {% trans "of the picture" %}</li>
+      {% if picture.extra_info.source_url %}
+      <li><a href="{{ picture.extra_info.source_url }}">{% trans "Source" %}</a> {% trans "of the picture" %}</li>
       {% endif %}
       <li><a href="{{ picture.xml_file.url }}">{% trans "Source XML file" %}</a></li>
       {% endif %}
       <li><a href="{{ picture.xml_file.url }}">{% trans "Source XML file" %}</a></li>
-      {% if extra_info.about and not hide_about %}
-      <li>{% trans "Picture on" %} <a href="{{ extra_info.about }}">{% trans "Editor's Platform" %}</a></li>
+      {% if picture.extra_info.about and not hide_about %}
+      <li>{% trans "Picture on" %} <a href="{{ picture.extra_info.about }}">{% trans "Editor's Platform" %}</a></li>
       {% endif %}
       {% if picture.wiki_link %}
       <li><a href="{{ picture.wiki_link }}">{% trans "Picture description on Wikipedia" %}</a></li>
       {% endif %}
       {% if picture.wiki_link %}
       <li><a href="{{ picture.wiki_link }}">{% trans "Picture description on Wikipedia" %}</a></li>
index fea5a5e..4337058 100644 (file)
@@ -37,7 +37,7 @@ def picture_list_thumb(request, filter=None, get_filter=None, template_name='pic
         book_list = book_list.filter(get_filter())
     book_list = book_list.order_by('sort_key_author')
     book_list = list(book_list)
         book_list = book_list.filter(get_filter())
     book_list = book_list.order_by('sort_key_author')
     book_list = list(book_list)
-    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
+    return render_to_response(template_name, {'book_list': book_list}, context_instance=RequestContext(request))
 
 
 def picture_detail(request, slug):
 
 
 def picture_detail(request, slug):
@@ -49,13 +49,11 @@ def picture_detail(request, slug):
     # for tag in picture.tags.iterator():
     #     categories.setdefault(tag.category, []).append(tag)
 
     # for tag in picture.tags.iterator():
     #     categories.setdefault(tag.category, []).append(tag)
 
-    themes = theme_things.get('theme', [])
-    things = theme_things.get('thing', [])
-
-    extra_info = picture.extra_info
-
-    return render_to_response("picture/picture_detail.html", locals(),
-                              context_instance=RequestContext(request))
+    return render_to_response("picture/picture_detail.html", {
+        'picture': picture,
+        'themes': theme_things.get('theme', []),
+        'things': theme_things.get('thing', []),
+    }, context_instance=RequestContext(request))
 
 
 def picture_viewer(request, slug):
 
 
 def picture_viewer(request, slug):
@@ -65,8 +63,10 @@ def picture_viewer(request, slug):
         have_sponsors = Sponsor.objects.filter(name=sponsor)
         if have_sponsors.exists():
             sponsors.append(have_sponsors[0])
         have_sponsors = Sponsor.objects.filter(name=sponsor)
         if have_sponsors.exists():
             sponsors.append(have_sponsors[0])
-    return render_to_response("picture/picture_viewer.html", locals(),
-                              context_instance=RequestContext(request))
+    return render_to_response("picture/picture_viewer.html", {
+        'picture': picture,
+        'sponsors': sponsors,
+    }, context_instance=RequestContext(request))
 
 
 # =========
 
 
 # =========
@@ -123,8 +123,10 @@ def picture_short(request, pk):
 @ssi_included
 def picturearea_short(request, pk):
     area = get_object_or_404(PictureArea, pk=pk)
 @ssi_included
 def picturearea_short(request, pk):
     area = get_object_or_404(PictureArea, pk=pk)
-    theme = area.tags.filter(category='theme')
-    theme = theme and theme[0] or None
-    thing = area.tags.filter(category='thing')
-    thing = thing and thing[0] or None
-    return render(request, 'picture/picturearea_short.html', locals())
+    themes = area.tags.filter(category='theme')
+    things = area.tags.filter(category='thing')
+    return render(request, 'picture/picturearea_short.html', {
+        'area': area,
+        'theme': themes[0] if themes else None,
+        'thing': things[0] if things else None,
+    })
index d17d212..bc0dee6 100644 (file)
@@ -16,7 +16,6 @@ from reporting.utils import render_to_pdf, render_to_csv, generated_file_view
 
 @staff_member_required
 def stats_page(request):
 
 @staff_member_required
 def stats_page(request):
-    media = BookMedia.objects.count()
     media_types = BookMedia.objects.values('type').annotate(count=Count('type')).order_by('type')
     for mt in media_types:
         mt['size'] = sum(b.file.size for b in BookMedia.objects.filter(type=mt['type']).iterator())
     media_types = BookMedia.objects.values('type').annotate(count=Count('type')).order_by('type')
     for mt in media_types:
         mt['size'] = sum(b.file.size for b in BookMedia.objects.filter(type=mt['type']).iterator())
@@ -27,18 +26,25 @@ def stats_page(request):
         else:
             mt['deprecated'] = '-'
 
         else:
             mt['deprecated'] = '-'
 
-    licenses = set((
+    licenses = set(
         (b.extra_info.get('license'), b.extra_info.get('license_description'))
         (b.extra_info.get('license'), b.extra_info.get('license_description'))
-        for b in Book.objects.all().iterator() if b.extra_info.get('license')))
+        for b in Book.objects.all().iterator() if b.extra_info.get('license'))
 
 
-    return render_to_response('reporting/main.html', locals(), context_instance=RequestContext(request))
+    return render_to_response('reporting/main.html', {
+        'media_types': media_types,
+        'licenses': licenses,
+    }, context_instance=RequestContext(request))
 
 
 @generated_file_view('reports/katalog.pdf', 'application/pdf',
                      send_name=lambda: 'wolnelektury_%s.pdf' % date.today(), signals=[Book.published])
 def catalogue_pdf(path):
     books_by_author, orphans, books_by_parent = Book.book_list()
 
 
 @generated_file_view('reports/katalog.pdf', 'application/pdf',
                      send_name=lambda: 'wolnelektury_%s.pdf' % date.today(), signals=[Book.published])
 def catalogue_pdf(path):
     books_by_author, orphans, books_by_parent = Book.book_list()
-    render_to_pdf(path, 'reporting/catalogue.texml', locals(), {
+    render_to_pdf(path, 'reporting/catalogue.texml', {
+        'books_by_author': books_by_author,
+        'orphans': orphans,
+        'book_by_parent': books_by_parent,
+    }, {
         "wl-logo.png": os.path.join(settings.STATIC_ROOT, "img/logo-big.png"),
     })
 
         "wl-logo.png": os.path.join(settings.STATIC_ROOT, "img/logo-big.png"),
     })
 
@@ -47,4 +53,8 @@ def catalogue_pdf(path):
                      send_name=lambda: 'wolnelektury_%s.csv' % date.today(), signals=[Book.published])
 def catalogue_csv(path):
     books_by_author, orphans, books_by_parent = Book.book_list()
                      send_name=lambda: 'wolnelektury_%s.csv' % date.today(), signals=[Book.published])
 def catalogue_csv(path):
     books_by_author, orphans, books_by_parent = Book.book_list()
-    render_to_csv(path, 'reporting/catalogue.csv', locals())
+    render_to_csv(path, 'reporting/catalogue.csv', {
+        'books_by_author': books_by_author,
+        'orphans': orphans,
+        'book_by_parent': books_by_parent,
+    })
index 49c9b70..15f01bf 100644 (file)
@@ -38,8 +38,9 @@ def like_book(request, slug):
 
 @login_required
 def my_shelf(request):
 
 @login_required
 def my_shelf(request):
-    books = Book.tagged.with_any(request.user.tag_set.all())
-    return render(request, 'social/my_shelf.html', locals())
+    return render(request, 'social/my_shelf.html', {
+        'books': Book.tagged.with_any(request.user.tag_set.all())
+    })
 
 
 class ObjectSetsFormView(AjaxableFormView):
 
 
 class ObjectSetsFormView(AjaxableFormView):
index b951cc4..836534e 100644 (file)
@@ -14,11 +14,15 @@ from django.views.decorators.cache import never_cache
 def wait(request, path):
     if WaitedFile.exists(path):
         file_url = join(WAITER_URL, path)
 def wait(request, path):
     if WaitedFile.exists(path):
         file_url = join(WAITER_URL, path)
+        waiting = None
     else:
     else:
-        file_url = ""
+        file_url = None
         waiting = get_object_or_404(WaitedFile, path=path)
 
     if request.is_ajax():
         return HttpResponse(file_url)
     else:
         waiting = get_object_or_404(WaitedFile, path=path)
 
     if request.is_ajax():
         return HttpResponse(file_url)
     else:
-        return render(request, "waiter/wait.html", locals())
+        return render(request, "waiter/wait.html", {
+            'waiting': waiting,
+            'file_url': file_url,
+        })