From: Radek Czajka Date: Thu, 13 Feb 2014 14:05:52 +0000 (+0100) Subject: Unused imports & whitespace X-Git-Url: https://git.mdrn.pl/wolnelektury.git/commitdiff_plain/dbb1ae2cf25105f7a3831961b08386a1326baef8 Unused imports & whitespace --- diff --git a/apps/ajaxable/utils.py b/apps/ajaxable/utils.py index 0c8fcd4ec..4a801206b 100755 --- a/apps/ajaxable/utils.py +++ b/apps/ajaxable/utils.py @@ -30,7 +30,7 @@ class JSONResponse(HttpResponse): kwargs.pop('mimetype', None) data = json.dumps(data) if callback: - data = callback + "(" + data + ");" + data = callback + "(" + data + ");" super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs) @@ -74,7 +74,7 @@ class AjaxableFormView(object): # override to customize form look template = "ajaxable/form.html" submit = _('Send') - + title = '' success_message = '' POST_login = False @@ -106,7 +106,7 @@ class AjaxableFormView(object): if form.is_valid(): add_args = self.success(form, request) response_data = { - 'success': True, + 'success': True, 'message': self.success_message, 'redirect': request.GET.get('next') } @@ -147,7 +147,7 @@ class AjaxableFormView(object): if self.placeholdize: form = placeholdized(form) context = { - self.formname: form, + self.formname: form, "title": title, "honeypot": self.honeypot, "placeholdize": self.placeholdize, @@ -162,12 +162,12 @@ class AjaxableFormView(object): context_instance=RequestContext(request)) def redirect_or_refresh(self, request, path, message=None): - """If the form is AJAX, refresh the page. If not, go to `path`.""" + """If the form is AJAX, refresh the page. If not, go to `path`.""" if request.is_ajax(): output = "" if message: output = "
" + message + "
" + output - return HttpResponse(output); + return HttpResponse(output) else: return HttpResponseRedirect(path) @@ -189,7 +189,7 @@ class AjaxableFormView(object): def success(self, form, request): """What to do when the form is valid. - + By default, just save the form. """ diff --git a/apps/api/handlers.py b/apps/api/handlers.py index 89c726f8c..e1792af13 100644 --- a/apps/api/handlers.py +++ b/apps/api/handlers.py @@ -4,7 +4,6 @@ # from datetime import datetime, timedelta import json -from urlparse import urljoin from django.conf import settings from django.contrib.sites.models import Site @@ -39,7 +38,7 @@ category_singular = { 'themes': 'theme', 'books': 'book', } -category_plural={} +category_plural = {} for k, v in category_singular.items(): category_plural[v] = k @@ -104,7 +103,6 @@ class BookMediaHandler(BaseHandler): @classmethod def director(cls, media): return media.extra_info.get('director_name', '') - class BookDetails(object): @@ -200,7 +198,7 @@ class AnonymousBooksHandler(AnonymousBaseHandler, BookDetails): books = Book.tagged.with_all(tags) else: books = Book.objects.all() - + if top_level: books = books.filter(parent=None) if audiobooks: @@ -297,7 +295,6 @@ class CollectionDetailHandler(BaseHandler, CollectionDetails): @piwik_track def read(self, request, slug): - print slug """ Returns details of a collection, identified by slug. """ try: return Collection.objects.get(slug=slug) @@ -386,7 +383,7 @@ class FragmentDetails(object): def href(cls, fragment): """ Returns URI in the API for the fragment. """ - return API_BASE + reverse("api_fragment", + return API_BASE + reverse("api_fragment", args=[fragment.book.slug, fragment.anchor]) @classmethod @@ -563,7 +560,7 @@ class CatalogueHandler(BaseHandler): if updated: changes['updated'] = updated - for book in Deleted.objects.filter(content_type=Book, + for book in Deleted.objects.filter(content_type=Book, deleted_at__gte=since, deleted_at__lt=until, created_at__lt=since).iterator(): @@ -628,7 +625,7 @@ class CatalogueHandler(BaseHandler): updated = [] deleted = [] - for tag in Tag.objects.filter(category__in=categories, + for tag in Tag.objects.filter(category__in=categories, changed_at__gte=since, changed_at__lt=until).iterator(): # only serve non-empty tags @@ -641,7 +638,7 @@ class CatalogueHandler(BaseHandler): changes['updated'] = updated for tag in Deleted.objects.filter(category__in=categories, - content_type=Tag, + content_type=Tag, deleted_at__gte=since, deleted_at__lt=until, created_at__lt=since).iterator(): diff --git a/apps/api/management/commands/mobileinit.py b/apps/api/management/commands/mobileinit.py index 91ee3b624..2102bbb9c 100755 --- a/apps/api/management/commands/mobileinit.py +++ b/apps/api/management/commands/mobileinit.py @@ -58,7 +58,7 @@ def pretty_size(size): value = re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, value) value = value.lower() value = re.sub(r'[^a-z0-9{|}]+', '~', value) - + return value.encode('ascii', 'ignore') @@ -113,7 +113,7 @@ def current(last_checked): 'initial.db-%d' % last_checked, target, ) - + book_sql = """ @@ -130,9 +130,9 @@ tag_sql = """ (:id, :category, :name, :sort_key, :book_ids); """ categories = {'author': 'autor', - 'epoch': 'epoka', - 'genre': 'gatunek', - 'kind': 'rodzaj', + 'epoch': 'epoka', + 'genre': 'gatunek', + 'kind': 'rodzaj', 'theme': 'motyw' } diff --git a/apps/api/models.py b/apps/api/models.py index 20dd12985..5a3d42440 100644 --- a/apps/api/models.py +++ b/apps/api/models.py @@ -34,6 +34,6 @@ def _pre_delete_handler(sender, instance, **kwargs): else: category = None content_type = ContentType.objects.get_for_model(sender) - Deleted.objects.create(content_type=content_type, object_id=instance.id, + Deleted.objects.create(content_type=content_type, object_id=instance.id, created_at=instance.created_at, category=category, slug=instance.slug) pre_delete.connect(_pre_delete_handler) diff --git a/apps/api/tests.py b/apps/api/tests.py index b72af1b22..0a638dc3f 100644 --- a/apps/api/tests.py +++ b/apps/api/tests.py @@ -16,7 +16,7 @@ import picture.tests @override_settings( - API_WAIT=-1, + API_WAIT=-1, CACHES = {'api': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}, 'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}, 'permanent': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}} @@ -35,10 +35,10 @@ class ChangesTest(ApiTest): book.save() changes = json.loads(self.client.get('/api/changes/0.json?book_fields=title&tag_fields=name').content) - self.assertEqual(changes['updated']['books'], + self.assertEqual(changes['updated']['books'], [{'id': book.id, 'title': book.title}], 'Invalid book format in changes') - self.assertEqual(changes['updated']['tags'], + self.assertEqual(changes['updated']['tags'], [{'id': tag.id, 'name': tag.name}], 'Invalid tag format in changes') @@ -157,5 +157,4 @@ class PictureTests(ApiTest): if import_form.is_valid(): import_form.save() - pic = Picture.objects.get(slug=slug) - + Picture.objects.get(slug=slug) diff --git a/apps/api/urls.py b/apps/api/urls.py index 0267ba097..7c12c017f 100644 --- a/apps/api/urls.py +++ b/apps/api/urls.py @@ -5,7 +5,7 @@ from django.conf.urls import patterns, url from django.views.decorators.csrf import csrf_exempt from django.views.generic import TemplateView -from piston.authentication import OAuthAuthentication, oauth_access_token +from piston.authentication import OAuthAuthentication, oauth_access_token from piston.resource import Resource from api import handlers diff --git a/apps/catalogue/__init__.py b/apps/catalogue/__init__.py index 1fbdc2093..2e7a89f90 100644 --- a/apps/catalogue/__init__.py +++ b/apps/catalogue/__init__.py @@ -39,7 +39,7 @@ class Settings(AppSettings): attname = 'ALL_%s_ZIP' % format_.upper() if hasattr(settings, attname): logging.warn("%s is deprecated, " - "use CATALOGUE_FORMAT_ZIPS[%s] instead", + "use CATALOGUE_FORMAT_ZIPS[%s] instead", attname, format_) value[format_] = getattr(settings, attname) return value diff --git a/apps/catalogue/feeds.py b/apps/catalogue/feeds.py index ddbcb1d6a..2411d015a 100644 --- a/apps/catalogue/feeds.py +++ b/apps/catalogue/feeds.py @@ -5,7 +5,6 @@ from django.contrib.sites.models import Site from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse -from django.db.models import Q from catalogue import models @@ -52,7 +51,7 @@ class AudiobookFeed(Feed): return item.name def item_categories(self, item): - return sorted(set(author.name for author in + return sorted(set(author.name for author in item.book.tags.filter(category='author').iterator())) def item_description(self, item): diff --git a/apps/catalogue/fields.py b/apps/catalogue/fields.py index 9d7dcf232..6080c2ab4 100644 --- a/apps/catalogue/fields.py +++ b/apps/catalogue/fields.py @@ -200,7 +200,7 @@ class BuildHtml(BuildEbook): short_text = truncate_html_words(text, 15) if text == short_text: short_text = '' - new_fragment = Fragment.objects.create(anchor=fragment.id, + new_fragment = Fragment.objects.create(anchor=fragment.id, book=book, text=text, short_text=short_text) new_fragment.save() diff --git a/apps/catalogue/import_utils.py b/apps/catalogue/import_utils.py index bf36ea57f..ca0c6efe5 100644 --- a/apps/catalogue/import_utils.py +++ b/apps/catalogue/import_utils.py @@ -14,4 +14,4 @@ class ORMDocProvider(DocProvider): if slug == self.book.slug: return open(self.book.xml_file.path) else: - return type(self.book).objects.get(slug=slug).xml_file \ No newline at end of file + return type(self.book).objects.get(slug=slug).xml_file diff --git a/apps/catalogue/management/commands/__init__.py b/apps/catalogue/management/commands/__init__.py index 8d1c8b69c..8b1378917 100644 --- a/apps/catalogue/management/commands/__init__.py +++ b/apps/catalogue/management/commands/__init__.py @@ -1 +1 @@ - + diff --git a/apps/catalogue/management/commands/importbooks.py b/apps/catalogue/management/commands/importbooks.py index 2a44d5aaf..d0d2f2294 100644 --- a/apps/catalogue/management/commands/importbooks.py +++ b/apps/catalogue/management/commands/importbooks.py @@ -52,7 +52,7 @@ class Command(BaseCommand): for ebook_format in Book.ebook_formats: if os.path.isfile(file_base + '.' + ebook_format): getattr(book, '%s_file' % ebook_format).save( - '%s.%s' % (book.slug, ebook_format), + '%s.%s' % (book.slug, ebook_format), File(file(file_base + '.' + ebook_format)), save=False ) @@ -65,7 +65,7 @@ class Command(BaseCommand): image_store = ImageStore(os.path.dirname(file_path)) picture = Picture.from_xml_file(file_path, image_store=image_store, overwrite=options.get('force')) except Exception, ex: - if continue_on_error: + if continue_on_error: print "%s: %s" % (file_path, ex) return else: @@ -77,10 +77,8 @@ class Command(BaseCommand): from django.db import transaction self.style = color_style() - + verbose = options.get('verbose') - force = options.get('force') - show_traceback = options.get('traceback', False) import_picture = options.get('import_picture') wait_until = None @@ -141,7 +139,7 @@ class Command(BaseCommand): files_imported += 1 transaction.commit() - + except (Book.AlreadyExists, Picture.AlreadyExists): print self.style.ERROR('%s: Book or Picture already imported. Skipping. To overwrite use --force.' % file_path) diff --git a/apps/catalogue/management/commands/pack.py b/apps/catalogue/management/commands/pack.py index 6ecf32d59..ba06341b8 100755 --- a/apps/catalogue/management/commands/pack.py +++ b/apps/catalogue/management/commands/pack.py @@ -2,9 +2,6 @@ # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # -import re -import sys -from cPickle import load, dump from optparse import make_option from django.core.management.base import BaseCommand diff --git a/apps/catalogue/management/commands/savemedia.py b/apps/catalogue/management/commands/savemedia.py index 49f1d484e..216c5e335 100755 --- a/apps/catalogue/management/commands/savemedia.py +++ b/apps/catalogue/management/commands/savemedia.py @@ -5,7 +5,6 @@ import os.path from django.core.management.base import BaseCommand -from django.core.files import File from catalogue.models import Book, BookMedia from catalogue.utils import ExistingFile diff --git a/apps/catalogue/models/book.py b/apps/catalogue/models/book.py index b9441c386..bd7d7e49a 100644 --- a/apps/catalogue/models/book.py +++ b/apps/catalogue/models/book.py @@ -128,7 +128,7 @@ class Book(models.Model): if self.has_media(type_): if type_ in Book.formats: return getattr(self, "%s_file" % type_) - else: + else: return self.media.filter(type=type_) else: return None @@ -140,7 +140,7 @@ class Book(models.Model): def get_ogg(self): return self.get_media("ogg") def get_daisy(self): - return self.get_media("daisy") + return self.get_media("daisy") def reset_short_html(self): if self.id is None: @@ -151,7 +151,7 @@ class Book(models.Model): for fragm in self.fragments.all().iterator(): fragm.reset_short_html() - try: + try: author = self.tags.filter(category='author')[0].sort_key except IndexError: author = u'' @@ -323,7 +323,7 @@ class Book(models.Model): if 'cover' not in dont_build: book.cover.build_delay() book.cover_thumb.build_delay() - + # No saves behind this point. if has_own_text: @@ -566,7 +566,7 @@ class Book(models.Model): 'title', 'parent', 'slug') if filter: books = books.filter(filter).distinct() - + book_ids = set(b['pk'] for b in books.values("pk").iterator()) for book in books.iterator(): parent = book.parent_id @@ -582,7 +582,7 @@ class Book(models.Model): for tag in Tag.objects.filter(category='author').iterator(): books_by_author[tag] = [] - for book in books_by_parent.get(None,()): + for book in books_by_parent.get(None, ()): authors = list(book.tags.filter(category='author')) if authors: for author in authors: diff --git a/apps/catalogue/models/bookmedia.py b/apps/catalogue/models/bookmedia.py index a62b4cf06..42781e9d0 100644 --- a/apps/catalogue/models/bookmedia.py +++ b/apps/catalogue/models/bookmedia.py @@ -82,10 +82,10 @@ class BookMedia(models.Model): audio = id3.ID3(self.file.path) artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1')) director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3')) - project = ", ".join([t.data for t in audio.getall('PRIV') - if t.owner=='wolnelektury.pl?project']) - funded_by = ", ".join([t.data for t in audio.getall('PRIV') - if t.owner=='wolnelektury.pl?funded_by']) + project = ", ".join([t.data for t in audio.getall('PRIV') + if t.owner == 'wolnelektury.pl?project']) + funded_by = ", ".join([t.data for t in audio.getall('PRIV') + if t.owner == 'wolnelektury.pl?funded_by']) except: pass elif self.type == 'ogg': @@ -113,14 +113,14 @@ class BookMedia(models.Model): if filetype == 'mp3': try: audio = id3.ID3(filepath) - return [t.data for t in audio.getall('PRIV') - if t.owner=='wolnelektury.pl?flac_sha1'][0] + return [t.data for t in audio.getall('PRIV') + if t.owner == 'wolnelektury.pl?flac_sha1'][0] except: return None elif filetype == 'ogg': try: audio = mutagen.File(filepath) - return audio.get('flac_sha1', [None])[0] + return audio.get('flac_sha1', [None])[0] except: return None else: diff --git a/apps/catalogue/models/tag.py b/apps/catalogue/models/tag.py index acfb9d8f3..ba219fc7c 100644 --- a/apps/catalogue/models/tag.py +++ b/apps/catalogue/models/tag.py @@ -26,7 +26,7 @@ TAG_CATEGORIES = ( class Tag(TagBase): """A tag attachable to books and fragments (and possibly anything). - + Used to represent searchable metadata (authors, epochs, genres, kinds), fragment themes (motifs) and some book hierarchy related kludges.""" name = models.CharField(_('name'), max_length=50, db_index=True) @@ -43,8 +43,8 @@ class Tag(TagBase): culturepl_link = models.CharField(blank=True, max_length=240) wiki_link = models.CharField(blank=True, max_length=240) - created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True) - changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True) + created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True) + changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True) class UrlDeprecationWarning(DeprecationWarning): pass @@ -113,11 +113,11 @@ class Tag(TagBase): objects = objects.exclude(pk__in=descendants_keys) return objects.count() - # I shouldn't break the get_count() api + # I shouldn't break the get_count() api # just to include pictures. def get_picture_count(self): from picture.models import Picture, PictureArea - + if self.category == 'book': # never used objects = Picture.objects.none() @@ -128,7 +128,7 @@ class Tag(TagBase): else: objects = Picture.tagged.with_all((self,)).order_by() return objects.count() - + @staticmethod def get_tag_list(tags): if isinstance(tags, basestring): @@ -146,7 +146,7 @@ class Tag(TagBase): else: try: real_tags.append(Tag.objects.exclude(category='book').get(slug=name)) - deprecated = True + deprecated = True except Tag.MultipleObjectsReturned, e: ambiguous_slugs.append(name) diff --git a/apps/catalogue/templatetags/catalogue_tags.py b/apps/catalogue/templatetags/catalogue_tags.py index c9bf3dda2..95288a404 100644 --- a/apps/catalogue/templatetags/catalogue_tags.py +++ b/apps/catalogue/templatetags/catalogue_tags.py @@ -14,9 +14,9 @@ from django.core.urlresolvers import reverse from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.utils.translation import ugettext as _ -from catalogue.utils import split_tags, related_tag_name as _related_tag_name +from catalogue.utils import related_tag_name as _related_tag_name from catalogue.models import Book, BookMedia, Fragment, Tag -from catalogue.constants import LICENSES, LANGUAGES_3TO2 +from catalogue.constants import LICENSES register = template.Library() @@ -55,7 +55,7 @@ def html_title_from_tags(tags): template = Template("{{ category }}: {{ tag.name }}") return capfirst(",
".join( template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags)) - + def simple_title(tags): title = [] @@ -186,12 +186,12 @@ def book_tree_csv(author, book_list, books_by_parent, depth=1, max_depth=3, deli return '"%s"' % s except ValueError: return s - + return "".join("""%(author)s%(d)s%(preindent)s%(title)s%(d)s%(postindent)s%(audiences)s%(d)s%(audiobook)s %(children)s""" % { "d": delimeter, "preindent": delimeter * (depth - 1), - "postindent": delimeter * (max_depth - depth), + "postindent": delimeter * (max_depth - depth), "depth": depth, "author": quote_if_necessary(author.name), "title": quote_if_necessary(book.title), @@ -285,7 +285,7 @@ def latest_blog_posts(feed_url, posts_to_show=5): posts = [] for i in range(posts_to_show): pub_date = feed['entries'][i].updated_parsed - published = datetime.date(pub_date[0], pub_date[1], pub_date[2] ) + published = datetime.date(pub_date[0], pub_date[1], pub_date[2]) posts.append({ 'title': feed['entries'][i].title, 'summary': feed['entries'][i].summary, @@ -367,7 +367,7 @@ def work_list(context, object_list): request = context.get('request') for obj in object_list: obj.object_type = type(obj).__name__ - + return locals() diff --git a/apps/catalogue/tests/book_import.py b/apps/catalogue/tests/book_import.py index 0d4f47041..08d5243eb 100644 --- a/apps/catalogue/tests/book_import.py +++ b/apps/catalogue/tests/book_import.py @@ -4,7 +4,7 @@ # from django.conf import settings -from django.core.files.base import ContentFile, File +from django.core.files.base import ContentFile from catalogue.test_utils import * from catalogue import models from librarian import WLURI @@ -118,7 +118,7 @@ class BookImportLogicTests(WLTestCase): """ Book with invalid characters in slug shouldn't be imported """ self.book_info.url = WLURI.from_slug(u"default_book") BOOK_TEXT = "" - book = models.Book.from_text_and_meta(ContentFile(BOOK_TEXT), self.book_info) + models.Book.from_text_and_meta(ContentFile(BOOK_TEXT), self.book_info) def test_book_replace_title(self): BOOK_TEXT = """""" @@ -438,7 +438,7 @@ class BookImportGenerateTest(WLTestCase): from catalogue.utils import get_dynamic_path out = get_dynamic_path(None, 'test-custom', ext='pdf') absoulute_path = path.join(settings.MEDIA_ROOT, out) - + if not path.exists(path.dirname(absoulute_path)): makedirs(path.dirname(absoulute_path)) diff --git a/apps/catalogue/tests/bookmedia.py b/apps/catalogue/tests/bookmedia.py index 0c015f209..2d3cf539d 100644 --- a/apps/catalogue/tests/bookmedia.py +++ b/apps/catalogue/tests/bookmedia.py @@ -4,7 +4,7 @@ # from django.conf import settings from os.path import basename, exists, join, dirname -from django.core.files.base import ContentFile, File +from django.core.files.base import ContentFile from catalogue.test_utils import * from catalogue import models, utils @@ -18,13 +18,13 @@ class BookMediaTests(WLTestCase): self.book = models.Book.objects.create(slug='test-book') def test_diacritics(self): - bm = models.BookMedia(book=self.book, type="ogg", + bm = models.BookMedia(book=self.book, type="ogg", name=u"Zażółć gęślą jaźń") bm.file.save(None, self.file) self.assertEqual(basename(bm.file.name), 'zazolc-gesla-jazn.ogg') def test_long_name(self): - bm = models.BookMedia(book=self.book, type="ogg", + bm = models.BookMedia(book=self.book, type="ogg", name="Some very very very very very very very very very very very very very very very very long file name") bm.file.save(bm.name, self.file) @@ -106,7 +106,7 @@ class BookMediaTests(WLTestCase): bm = models.BookMedia(book=self.book, type='ogg', name="Title") bm.file.save(None, self.file) bm.save() - + zip_url = self.book.zip_audiobooks('ogg') self.assertEqual('zip/'+self.book.slug+'_ogg.zip', zip_url) self.assertTrue(exists(join(settings.MEDIA_ROOT, zip_url))) diff --git a/apps/catalogue/tests/cover.py b/apps/catalogue/tests/cover.py index b73b387d4..0e08556b4 100755 --- a/apps/catalogue/tests/cover.py +++ b/apps/catalogue/tests/cover.py @@ -42,7 +42,7 @@ class CoverTests(WLTestCase): parent = Book.from_text_and_meta(ContentFile(self.TEXT), self.parent, overwrite=True) self.assertEqual(parent_cover_changed.call_count, 0) - + # Now change cover in parent. parent_cover_changed.reset_mock() self.parent.cover_url = "http://example.com/other-cover.jpg" diff --git a/apps/catalogue/utils.py b/apps/catalogue/utils.py index 884c250d3..98ee36c04 100644 --- a/apps/catalogue/utils.py +++ b/apps/catalogue/utils.py @@ -43,7 +43,7 @@ def split_tags(tags, initial=None): result = {} else: result = initial - + for tag in tags: result.setdefault(tag.category, []).append(tag) return result @@ -149,7 +149,7 @@ def remove_zip(zip_slug): class AttachmentHttpResponse(HttpResponse): """Response serving a file to be downloaded. """ - def __init__ (self, file_path, file_name, mimetype): + def __init__(self, file_path, file_name, mimetype): super(AttachmentHttpResponse, self).__init__(mimetype=mimetype) self['Content-Disposition'] = 'attachment; filename=%s' % file_name self.file_path = file_path @@ -163,15 +163,15 @@ class MultiQuerySet(object): def __init__(self, *args, **kwargs): self.querysets = args self._count = None - + def count(self): if not self._count: self._count = sum(len(qs) for qs in self.querysets) return self._count - + def __len__(self): return self.count() - + def __getitem__(self, item): try: indices = (offset, stop, step) = item.indices(self.count()) @@ -197,7 +197,7 @@ class SortedMultiQuerySet(MultiQuerySet): self.order_by = kwargs.pop('order_by', None) self.sortfn = kwargs.pop('sortfn', None) if self.order_by is not None: - self.sortfn = lambda a, b: cmp(getattr(a, self.order_by), + self.sortfn = lambda a, b: cmp(getattr(a, self.order_by), getattr(b, self.order_by)) super(SortedMultiQuerySet, self).__init__(*args, **kwargs) @@ -238,7 +238,7 @@ class SortedMultiQuerySet(MultiQuerySet): skipped += 1 continue # continue next item items.append(candidate) - + return items diff --git a/apps/catalogue/views.py b/apps/catalogue/views.py index 65b9c6c51..92469d775 100644 --- a/apps/catalogue/views.py +++ b/apps/catalogue/views.py @@ -9,7 +9,7 @@ from django.conf import settings from django.core.cache import get_cache from django.template import RequestContext from django.template.loader import render_to_string -from django.shortcuts import render_to_response, get_object_or_404, redirect +from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect from django.core.urlresolvers import reverse from django.db.models import Q @@ -30,14 +30,14 @@ from pdcounter import views as pdcounter_views from suggest.forms import PublishingSuggestForm from picture.models import Picture, PictureArea from picture.views import picture_list_thumb -import logging + 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/' + get_language() + cache_key = 'catalogue.catalogue/' + get_language() output = permanent_cache.get(cache_key) if output is None: @@ -52,8 +52,8 @@ def catalogue(request): render_tag_list = lambda x: render_to_string( 'catalogue/tag_list.html', tag_list(x)) - has_pictures = lambda x: filter(lambda y: y.picture_count>0, x) - has_books = lambda x: filter(lambda y: y.book_count>0, x) + 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) @@ -71,8 +71,7 @@ def catalogue(request): output[category] = render_tag_list(tags) else: output[category] = render_split(tags) - - + output['collections'] = render_to_string( 'catalogue/collection_list.html', collection_list(collections)) permanent_cache.set(cache_key, output) @@ -224,8 +223,8 @@ def tagged_object_list(request, tags=''): if area_keys: related_tags = PictureArea.tags.usage(counts=True, filters={'pk__in': area_keys}) - related_tags = (tag for tag in related_tags if tag not in fragment_tags) - + related_tags = (tag for tag in related_tags if tag not in fragment_tags) + categories = split_tags(related_tags, categories) # we want the Pictures to go first @@ -238,7 +237,7 @@ def tagged_object_list(request, tags=''): books = models.Book.tagged_top_level(tags).order_by('sort_key_author') pictures = Picture.tagged.with_all(tags).order_by('sort_key_author') - + related_counts = {} if books.count() > 0: # get related tags from `tag_counter` and `theme_counter` @@ -496,7 +495,7 @@ def find_best_matches(query, user=None): book_titles = set(match.pretty_title().lower() for match in result if isinstance(match, models.Book)) authors = set(match.name.lower() for match in result - if isinstance(match, models.Tag) and match.category=='author') + if isinstance(match, models.Tag) and match.category == 'author') result = tuple(res for res in result if not ( (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles) or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors) diff --git a/apps/chunks/admin.py b/apps/chunks/admin.py index 614e4e85b..61e9f8757 100644 --- a/apps/chunks/admin.py +++ b/apps/chunks/admin.py @@ -14,4 +14,4 @@ class AttachmentAdmin(admin.ModelAdmin): list_display = ('key',) search_fields = ('key',) -admin.site.register(Attachment, AttachmentAdmin) \ No newline at end of file +admin.site.register(Attachment, AttachmentAdmin) diff --git a/apps/dictionary/models.py b/apps/dictionary/models.py index 375bb22ca..7df3d75e3 100644 --- a/apps/dictionary/models.py +++ b/apps/dictionary/models.py @@ -27,9 +27,9 @@ def build_notes(book): from librarian import html for anchor, text_str, html_str in html.extract_annotations(book.html_file.path): Note.objects.create(book=book, anchor=anchor, - html=html_str, + html=html_str, sort_key=sortify(text_str).strip()[:128]) - + def notes_from_book(sender, **kwargs): build_notes.delay(sender) Book.html_built.connect(notes_from_book) diff --git a/apps/dictionary/tests.py b/apps/dictionary/tests.py index 27285cc14..e88fe507d 100755 --- a/apps/dictionary/tests.py +++ b/apps/dictionary/tests.py @@ -5,7 +5,6 @@ from django.core.files.base import ContentFile from catalogue.test_utils import * from catalogue.models import Book -from dictionary.models import Note class DictionaryTests(WLTestCase): diff --git a/apps/funding/forms.py b/apps/funding/forms.py index 64cceb6ad..6ed9076dd 100644 --- a/apps/funding/forms.py +++ b/apps/funding/forms.py @@ -48,7 +48,7 @@ class FundingForm(forms.Form): name=self.cleaned_data['name'], email=self.cleaned_data['email'], amount=self.cleaned_data['amount'], - language_code = get_language(), + language_code=get_language(), ) funding.perks = funding.offer.get_perks(funding.amount) return funding diff --git a/apps/funding/management/commands/funding_notify.py b/apps/funding/management/commands/funding_notify.py index a583b2785..305127629 100755 --- a/apps/funding/management/commands/funding_notify.py +++ b/apps/funding/management/commands/funding_notify.py @@ -14,7 +14,7 @@ class Command(BaseCommand): help = 'Sends relevant funding notifications.' def handle(self, **options): - + from datetime import date, timedelta from funding.models import Offer from funding import app_settings @@ -27,7 +27,7 @@ class Command(BaseCommand): offer.notify_end() current = Offer.current() - if (current is not None and + if (current is not None and current.end <= date.today() + timedelta(app_settings.DAYS_NEAR - 1) and not current.notified_near): if verbose: diff --git a/apps/funding/models.py b/apps/funding/models.py index 1eff8b4c6..800a15a3c 100644 --- a/apps/funding/models.py +++ b/apps/funding/models.py @@ -10,7 +10,7 @@ from django.conf import settings from django.template.loader import render_to_string from django.db import models from django.utils.timezone import utc -from django.utils.translation import ugettext_lazy as _, ugettext, override +from django.utils.translation import ugettext_lazy as _, override import getpaid from catalogue.models import Book from catalogue.utils import get_random_hash, related_tag_name @@ -31,8 +31,8 @@ class Offer(models.Model): redakcja_url = models.URLField(_('redakcja URL'), blank=True) book = models.ForeignKey(Book, null=True, blank=True, help_text=_('Published book.')) - cover = models.ImageField(_('Cover'), upload_to = 'funding/covers') - poll = models.ForeignKey(Poll, help_text = _('Poll'), null = True, blank = True, on_delete = models.SET_NULL) + cover = models.ImageField(_('Cover'), upload_to='funding/covers') + poll = models.ForeignKey(Poll, help_text=_('Poll'), null=True, blank=True, on_delete=models.SET_NULL) notified_near = models.DateTimeField(_('Near-end notifications sent'), blank=True, null=True) notified_end = models.DateTimeField(_('End notifications sent'), blank=True, null=True) @@ -41,7 +41,7 @@ class Offer(models.Model): return u'' % self.cover.url cover_img_tag.short_description = _('Cover preview') cover_img_tag.allow_tags = True - + class Meta: verbose_name = _('offer') verbose_name_plural = _('offers') @@ -54,7 +54,7 @@ class Offer(models.Model): return reverse('funding_offer', args=[self.slug]) def save(self, *args, **kw): - published_now = (self.book_id is not None and + published_now = (self.book_id is not None and self.pk is not None and type(self).objects.values('book').get(pk=self.pk)['book'] != self.book_id) retval = super(Offer, self).save(*args, **kw) @@ -110,7 +110,7 @@ class Offer(models.Model): def get_perks(self, amount=None): """ Finds all the perks for the offer. - + If amount is provided, returns the perks you get for it. """ @@ -183,7 +183,7 @@ class Offer(models.Model): class Perk(models.Model): """ A perk offer. - + If no attached to a particular Offer, applies to all. """ @@ -214,7 +214,7 @@ class Funding(models.Model): amount = models.DecimalField(_('amount'), decimal_places=2, max_digits=10) payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True) perks = models.ManyToManyField(Perk, verbose_name=_('perks'), blank=True) - language_code = models.CharField(max_length = 2, null = True, blank = True) + language_code = models.CharField(max_length=2, null=True, blank=True) notifications = models.BooleanField(_('notifications'), default=True, db_index=True) notify_key = models.CharField(max_length=32) diff --git a/apps/funding/templatetags/funding_tags.py b/apps/funding/templatetags/funding_tags.py index 0d6064f70..1a7c872a4 100755 --- a/apps/funding/templatetags/funding_tags.py +++ b/apps/funding/templatetags/funding_tags.py @@ -10,7 +10,7 @@ register = template.Library() @register.inclusion_tag("funding/tags/funding.html", takes_context=True) -def funding(context, offer=None, link=False, closeable=False, show_title=True, show_title_calling = True, add_class=""): +def funding(context, offer=None, link=False, closeable=False, show_title=True, show_title_calling=True, add_class=""): if offer is None and context.get('funding_no_show_current') is None: offer = Offer.current() is_current = True @@ -41,7 +41,7 @@ def offer_status(offer): return { 'offer': offer, } - + @register.inclusion_tag("funding/tags/offer_status_more.html") def offer_status_more(offer): return { diff --git a/apps/funding/tests.py b/apps/funding/tests.py index 30583f11f..6dbfbb457 100644 --- a/apps/funding/tests.py +++ b/apps/funding/tests.py @@ -4,7 +4,7 @@ # from datetime import date, timedelta from django.test import TestCase -from .models import Offer, Perk, Funding +from .models import Offer, Perk class PerksTest(TestCase): diff --git a/apps/funding/urls.py b/apps/funding/urls.py index 3e55ba4b4..2b8e5d672 100644 --- a/apps/funding/urls.py +++ b/apps/funding/urls.py @@ -4,7 +4,6 @@ # from django.conf.urls import patterns, url, include -from .models import Offer from .views import (WLFundView, OfferDetailView, OfferListView, ThanksView, NoThanksView, CurrentView, DisableNotifications) @@ -17,11 +16,11 @@ urlpatterns = patterns('', url(r'^lektura/$', OfferListView.as_view(), name='funding'), url(r'^lektura/(?P[^/]+)/$', OfferDetailView.as_view(), name='funding_offer'), url(r'^pozostale/$', WLFundView.as_view(), name='funding_wlfund'), - + url(r'^dziekujemy/$', ThanksView.as_view(), name='funding_thanks'), url(r'^niepowodzenie/$', NoThanksView.as_view(), name='funding_nothanks'), url(r'^wylacz_email/$', DisableNotifications.as_view(), name='funding_disable_notifications'), - + url(r'^getpaid/', include('getpaid.urls')), ) diff --git a/apps/funding/utils.py b/apps/funding/utils.py index ff6e9f4a1..c16c9d93d 100644 --- a/apps/funding/utils.py +++ b/apps/funding/utils.py @@ -11,8 +11,8 @@ from fnpdjango.utils.text.slughifi import char_map # with the notable exception of backslash. sane_in_payu_title = re.escape( string.uppercase + - string.lowercase + - u'ąćęłńóśźżĄĆĘŁŃÓŚŹŻ' + + string.lowercase + + u'ąćęłńóśźżĄĆĘŁŃÓŚŹŻ' + string.digits + ' ' + "".join(set(string.punctuation) - set('\\')) diff --git a/apps/funding/views.py b/apps/funding/views.py index dbbe21986..9dd18ccd4 100644 --- a/apps/funding/views.py +++ b/apps/funding/views.py @@ -2,14 +2,11 @@ # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # -from datetime import date -from django.views.decorators.cache import never_cache from django.core.urlresolvers import reverse from django.http import Http404 from django.shortcuts import redirect, get_object_or_404 from django.views.decorators.csrf import csrf_exempt -from django.views.generic import TemplateView, FormView, DetailView, ListView -import getpaid.backends.payu +from django.views.generic import TemplateView, FormView, ListView from getpaid.models import Payment from . import app_settings from .forms import FundingForm @@ -52,7 +49,7 @@ class WLFundView(TemplateView): ctx = super(WLFundView, self).get_context_data() offers = [] - + for o in Offer.past(): if o.is_win(): o.wlfund = o.sum() - o.target @@ -149,7 +146,7 @@ class DisableNotifications(TemplateView): @csrf_exempt def dispatch(self, request): - self.object = get_object_or_404(Funding, + self.object = get_object_or_404(Funding, email=request.GET.get('email'), notify_key=request.GET.get('key')) return super(DisableNotifications, self).dispatch(request) diff --git a/apps/funding/widgets.py b/apps/funding/widgets.py index cd7bf9b0d..8dc9742ce 100644 --- a/apps/funding/widgets.py +++ b/apps/funding/widgets.py @@ -3,7 +3,6 @@ # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from decimal import Decimal -from django.conf import settings from django import forms from django.template.loader import render_to_string @@ -37,5 +36,3 @@ class PerksAmountWidget(forms.Textarea): def value_from_datadict(self, data, files, name): num_str = data.get(self.perks_input_name(name)) or data[name] return num_str.replace(',', '.') - - diff --git a/apps/lesmianator/__init__.py b/apps/lesmianator/__init__.py index f3aa78cd8..54eee5b94 100644 --- a/apps/lesmianator/__init__.py +++ b/apps/lesmianator/__init__.py @@ -5,6 +5,4 @@ # Leśmianator do działania wymaga pliku dictionary.p w katalogu aplikacji # plik ten powinien zawierać słownik postaci: -# <3-znakowy ciąg> => => -# -# automat generujący taki słownik zostanie dodany później :) +# <3-znakowy ciąg> => => diff --git a/apps/lesmianator/management/commands/lesmianator.py b/apps/lesmianator/management/commands/lesmianator.py index 5412bee81..b2341ab31 100644 --- a/apps/lesmianator/management/commands/lesmianator.py +++ b/apps/lesmianator/management/commands/lesmianator.py @@ -3,8 +3,7 @@ # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # import re -import sys -from cPickle import load, dump +from cPickle import dump from optparse import make_option from django.core.management.base import BaseCommand @@ -78,7 +77,7 @@ class Command(BaseCommand): text = unicode(m.group(1), 'utf-8').lower() for letter in text: mydict = lesmianator.setdefault(last_word, {}) - myval = mydict.setdefault(letter, 0) + mydict.setdefault(letter, 0) mydict[letter] += 1 last_word = last_word[-2:] + letter f.close() @@ -99,4 +98,4 @@ class Command(BaseCommand): dump(lesmianator, open(path, 'w')) if verbose >= 1: print "%d processed, %d skipped" % (processed, skipped) - print "Results dumped to %s" % path + print "Results dumped to %s" % path diff --git a/apps/lesmianator/models.py b/apps/lesmianator/models.py index b462dcaa1..83e82135c 100644 --- a/apps/lesmianator/models.py +++ b/apps/lesmianator/models.py @@ -9,11 +9,9 @@ from StringIO import StringIO from django.core.files.base import ContentFile from django.db import models -from django.db.models import permalink from django.utils.timezone import utc from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse -from django.db.models.signals import m2m_changed from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic @@ -138,7 +136,7 @@ class Continuations(models.Model): mydict[letter] += 1 last_word = last_word[-length+1:] + letter # add children - return reduce(cls.join_conts, + return reduce(cls.join_conts, (cls.get(child) for child in book.children.all().iterator()), conts) diff --git a/apps/lesmianator/views.py b/apps/lesmianator/views.py index e74d21fea..1ef4397b3 100644 --- a/apps/lesmianator/views.py +++ b/apps/lesmianator/views.py @@ -2,10 +2,8 @@ # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # -from django.http import Http404 from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext -from django.contrib.auth.decorators import login_required from django.views.decorators import cache from catalogue.utils import get_random_hash @@ -17,7 +15,7 @@ def main_page(request): last = Poem.objects.all().order_by('-created_at')[:10] shelves = Tag.objects.filter(user__username='lesmianator') - return render_to_response('lesmianator/lesmianator.html', + return render_to_response('lesmianator/lesmianator.html', {"last": last, "shelves": shelves}, context_instance=RequestContext(request)) @@ -29,7 +27,7 @@ def new_poem(request): p = Poem(slug=get_random_hash(text), text=text, created_by=user) p.save() - return render_to_response('lesmianator/poem.html', + return render_to_response('lesmianator/poem.html', {"poem": p}, context_instance=RequestContext(request)) @@ -43,7 +41,7 @@ def poem_from_book(request, slug): p.created_from = [book.id] p.save() - return render_to_response('lesmianator/poem.html', + return render_to_response('lesmianator/poem.html', {"poem": p, "books": [book], "book": book}, context_instance=RequestContext(request)) @@ -60,7 +58,7 @@ def poem_from_set(request, shelf): book = books[0] if len(books) == 1 else None - return render_to_response('lesmianator/poem.html', + return render_to_response('lesmianator/poem.html', {"poem": p, "shelf": tag, "books": books, "book": book}, context_instance=RequestContext(request)) @@ -73,7 +71,7 @@ def get_poem(request, poem): else: books = book = None - return render_to_response('lesmianator/poem.html', + return render_to_response('lesmianator/poem.html', {"poem": p, "books": books, "book": book}, context_instance=RequestContext(request)) diff --git a/apps/libraries/models.py b/apps/libraries/models.py index 96473eb03..c83afbbba 100644 --- a/apps/libraries/models.py +++ b/apps/libraries/models.py @@ -9,29 +9,29 @@ from django.utils.translation import ugettext_lazy as _ class Catalog(models.Model): """Represents a dictionary of libraries""" - name = models.CharField(_('name'), max_length = 120, null = False) - slug = models.SlugField(_('slug'), max_length = 120, unique = True, db_index = True) + name = models.CharField(_('name'), max_length=120, null=False) + slug = models.SlugField(_('slug'), max_length=120, unique=True, db_index=True) class Meta: verbose_name = _('catalog') verbose_name_plural = _('catalogs') - + def __unicode__(self): return self.name - + @models.permalink def get_absolute_url(self): return ('libraries_catalog_view', [self.slug]) - - + + class Library(models.Model): """Represent a single library in the libraries dictionary""" - name = models.CharField(_('name'), max_length = 120, blank = True) - slug = models.SlugField(_('slug'), max_length = 120, unique = True, db_index = True, null = True) - catalog = models.ForeignKey(Catalog, null = False, related_name = 'libraries', on_delete = models.PROTECT) - url = models.CharField(_('url'), max_length = 120, blank = True) - description = models.TextField(_('description'), blank = True) + name = models.CharField(_('name'), max_length=120, blank=True) + slug = models.SlugField(_('slug'), max_length=120, unique=True, db_index=True, null=True) + catalog = models.ForeignKey(Catalog, null=False, related_name='libraries', on_delete=models.PROTECT) + url = models.CharField(_('url'), max_length=120, blank=True) + description = models.TextField(_('description'), blank=True) class Meta: verbose_name = _('library') diff --git a/apps/libraries/views.py b/apps/libraries/views.py index 83ab6b14e..7e245adbd 100644 --- a/apps/libraries/views.py +++ b/apps/libraries/views.py @@ -3,7 +3,7 @@ # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.shortcuts import render_to_response, get_object_or_404 -from django.template import RequestContext, Template, TemplateSyntaxError +from django.template import RequestContext from libraries.models import Catalog, Library @@ -11,14 +11,14 @@ from libraries.models import Catalog, Library def main_view(request): context = RequestContext(request) context['catalogs'] = Catalog.objects.all() - return render_to_response('libraries/main_view.html', context_instance = context) + return render_to_response('libraries/main_view.html', context_instance=context) def catalog_view(request, slug): context = RequestContext(request) - context['catalog'] = get_object_or_404(Catalog.objects.filter(slug = slug).select_related()) - return render_to_response('libraries/catalog_view.html', context_instance = context) + context['catalog'] = get_object_or_404(Catalog.objects.filter(slug=slug).select_related()) + return render_to_response('libraries/catalog_view.html', context_instance=context) def library_view(request, catalog_slug, slug): context = RequestContext(request) - context['library'] = get_object_or_404(Library.objects.filter(slug = slug).filter(catalog__slug = catalog_slug)) - return render_to_response('libraries/library_view.html', context_instance = context) + context['library'] = get_object_or_404(Library.objects.filter(slug=slug).filter(catalog__slug=catalog_slug)) + return render_to_response('libraries/library_view.html', context_instance=context) diff --git a/apps/oai/handlers.py b/apps/oai/handlers.py index 142b81ff2..197ca7987 100644 --- a/apps/oai/handlers.py +++ b/apps/oai/handlers.py @@ -6,14 +6,10 @@ from oaipmh import server, common, metadata, error from catalogue.models import Book, Tag from api.models import Deleted from api.handlers import WL_BASE -from librarian.dcparser import BookInfo from librarian import WLURI from django.contrib.contenttypes.models import ContentType -from django.contrib.auth.models import User from datetime import datetime from lxml import etree -from lxml.etree import ElementTree -from django.db.models import Q from django.conf import settings from django.contrib.sites.models import Site from django.utils import timezone @@ -21,7 +17,7 @@ from django.utils import timezone make_time_naive = lambda d: timezone.localtime(d).replace(tzinfo=None) -WL_DC_READER_XPATH = '(.|*)/rdf:RDF/rdf:Description/%s/text()' +WL_DC_READER_XPATH = '(.|*)/rdf:RDF/rdf:Description/%s/text()' wl_dc_reader = metadata.MetadataReader( fields={ 'title': ('textList', WL_DC_READER_XPATH % 'dc:title'), diff --git a/apps/oai/tests/oaipmhapi.py b/apps/oai/tests/oaipmhapi.py index 15f3ff3aa..db57bc18b 100644 --- a/apps/oai/tests/oaipmhapi.py +++ b/apps/oai/tests/oaipmhapi.py @@ -4,7 +4,6 @@ # from catalogue.test_utils import WLTestCase from catalogue import models -from nose.tools import raises from oai.handlers import * from oaipmh.server import * from os import path @@ -29,9 +28,9 @@ class BookMetadataTest(WLTestCase): self.xml = XMLTreeServer(self.catalogue, mr, nsmap) def test_get_record(self): - sch = self.xml.getRecord(identifier='lubie-kiedy-kobieta', + self.xml.getRecord(identifier='lubie-kiedy-kobieta', metadataPrefix='oai_dc') - sch = self.xml.listRecords(metadataPrefix='oai_dc') + self.xml.listRecords(metadataPrefix='oai_dc') def test_selecting(self): records, token = self.catalogue.listRecords(**{'set': 'epoch:starozytnosc'}) diff --git a/apps/oai/views.py b/apps/oai/views.py index 7155d69fb..100267131 100644 --- a/apps/oai/views.py +++ b/apps/oai/views.py @@ -3,10 +3,10 @@ # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from oai.handlers import Catalogue, NS_DCTERMS, nsdcterms -from oaipmh.server import ServerBase, oai_dc_writer, NS_OAIDC, NS_DC, NS_XSI, nsoaidc, nsdc +from oaipmh.server import ServerBase, NS_OAIDC, NS_DC, NS_XSI, nsoaidc, nsdc from oaipmh.metadata import MetadataRegistry from django.http import HttpResponse -from lxml.etree import tostring, SubElement +from lxml.etree import SubElement @@ -29,12 +29,12 @@ def fbc_oai_dc_writer(element, metadata): for value in map.get(name, []): e = SubElement(e_dc, nsdc(name)) e.text = value - + def qdc_writer(element, metadata): """FBC notified us that original writer does not output all necessary namespace declarations. """ - nsmap={'oai_dc': NS_OAIDC, 'dc': NS_DC, 'xsi': NS_XSI, 'dcterms': NS_DCTERMS} + nsmap = {'oai_dc': NS_OAIDC, 'dc': NS_DC, 'xsi': NS_XSI, 'dcterms': NS_DCTERMS} map = metadata.getMap() for name in [ 'title', 'creator', 'subject', 'description', 'publisher', diff --git a/apps/opds/views.py b/apps/opds/views.py index 23c320e62..4dd1ca220 100644 --- a/apps/opds/views.py +++ b/apps/opds/views.py @@ -16,7 +16,7 @@ from django.contrib.sites.models import Site from basicauth import logged_in_or_basicauth, factory_decorator from catalogue.models import Book, Tag -from search.views import Search, SearchResult +from search.views import Search import operator import logging import re @@ -111,6 +111,7 @@ class OPDSFeed(Atom1Feed): u"length": self._book_parent_img_size, u"type": u"image/png"}) if item['pubdate'] is not None: + # FIXME: rfc3339_date is undefined, is this ever run? handler.addQuickElement(u"updated", rfc3339_date(item['pubdate']).decode('utf-8')) # Author information. @@ -127,6 +128,7 @@ class OPDSFeed(Atom1Feed): if item['unique_id'] is not None: unique_id = item['unique_id'] else: + # FIXME: get_tag_uri is undefined, is this ever run? unique_id = get_tag_uri(item['link'], item['pubdate']) handler.addQuickElement(u"id", unique_id) @@ -222,7 +224,7 @@ class ByCategoryFeed(Feed): author_link = u"http://wolnelektury.pl/" def get_object(self, request, category): - feed = [feed for feed in _root_feeds if feed['category']==category] + feed = [feed for feed in _root_feeds if feed['category'] == category] if feed: feed = feed[0] else: diff --git a/apps/pdcounter/admin.py b/apps/pdcounter/admin.py index f946cad00..e2e3fc310 100644 --- a/apps/pdcounter/admin.py +++ b/apps/pdcounter/admin.py @@ -9,7 +9,7 @@ from pdcounter.models import BookStub, Author class BookStubAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'slug', 'pd') - search_fields = ('title','author') + search_fields = ('title', 'author') ordering = ('title',) prepopulated_fields = {'slug': ('title',)} diff --git a/apps/pdcounter/models.py b/apps/pdcounter/models.py index 1e441ac64..064661c9d 100644 --- a/apps/pdcounter/models.py +++ b/apps/pdcounter/models.py @@ -93,7 +93,7 @@ if not settings.NO_SEARCH_INDEX: import search idx = search.Index() idx.index_tags(instance, remove_only=not 'created' in kwargs) - + post_delete.connect(update_index, Author) post_delete.connect(update_index, BookStub) post_save.connect(update_index, Author) diff --git a/apps/pdcounter/templatetags/time_tags.py b/apps/pdcounter/templatetags/time_tags.py index b8cc57123..7ea5c6055 100755 --- a/apps/pdcounter/templatetags/time_tags.py +++ b/apps/pdcounter/templatetags/time_tags.py @@ -20,7 +20,7 @@ def date_to_utc(date, day_end=False): """ if day_end: date += datetime.timedelta(1) - localtime = datetime.datetime.combine(date, datetime.time(0,0)) + localtime = datetime.datetime.combine(date, datetime.time(0, 0)) return timezone.utc.normalize( pytz.timezone(settings.TIME_ZONE).localize(localtime) ) diff --git a/apps/picture/models.py b/apps/picture/models.py index a0179de53..2707e088e 100644 --- a/apps/picture/models.py +++ b/apps/picture/models.py @@ -12,16 +12,13 @@ from django.utils.datastructures import SortedDict from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.core.cache import get_cache -from catalogue.utils import split_tags, related_tag_name -from django.utils.safestring import mark_safe +from catalogue.utils import split_tags from fnpdjango.utils.text.slughifi import slughifi from picture import tasks from StringIO import StringIO import jsonfield import itertools import logging -from sorl.thumbnail import get_thumbnail, default -from .engine import CustomCroppingEngine from PIL import Image @@ -40,9 +37,9 @@ picture_storage = FileSystemStorage(location=path.join( class PictureArea(models.Model): picture = models.ForeignKey('picture.Picture', related_name='areas') area = jsonfield.JSONField(_('area'), default={}, editable=False) - kind = models.CharField(_('kind'), max_length=10, blank=False, - null=False, db_index=True, - choices=(('thing', _('thing')), + kind = models.CharField(_('kind'), max_length=10, blank=False, + null=False, db_index=True, + choices=(('thing', _('thing')), ('theme', _('theme')))) objects = models.Manager() @@ -72,7 +69,7 @@ class PictureArea(models.Model): short_html = permanent_cache.get(cache_key) else: short_html = None - + if short_html is not None: return mark_safe(short_html) else: @@ -166,7 +163,7 @@ class Picture(models.Model): if not isinstance(xml_file, File): xml_file = File(open(xml_file)) close_xml_file = True - + try: # use librarian to parse meta-data if image_store is None: @@ -278,8 +275,8 @@ class Picture(models.Model): from PIL import ImageDraw, ImageFont from librarian import get_resource - annotated = Image.new(img.mode, - (img.size[0], img.size[1] + 40), + annotated = Image.new(img.mode, + (img.size[0], img.size[1] + 40), (255, 255, 255) ) annotated.paste(img, (0, 0)) @@ -332,12 +329,12 @@ class Picture(models.Model): def reset_short_html(self): if self.id is None: return - + type(self).objects.filter(pk=self.pk).update(_related_info=None) for area in self.areas.all().iterator(): area.reset_short_html() - try: + try: author = self.tags.filter(category='author')[0].sort_key except IndexError: author = u'' @@ -402,13 +399,13 @@ class Picture(models.Model): tag_info["name_%s" % lc] = tag_name cat.append(tag_info) rel['tags'][category] = cat - + if self.pk: type(self).objects.filter(pk=self.pk).update(_related_info=rel) return rel - # copied from book.py, figure out + # copied from book.py, figure out def related_themes(self): # self.theme_counter hides a computation, so a line below actually makes sense theme_counter = self.theme_counter @@ -462,7 +459,7 @@ class Picture(models.Model): if tags is None: tags = {} for area in PictureArea.objects.filter(picture=self).order_by().iterator(): - for tag in area.tags.filter(category__in=('theme','thing')).order_by().iterator(): + for tag in area.tags.filter(category__in=('theme', 'thing')).order_by().iterator(): tags[tag.pk] = tags.get(tag.pk, 0) + 1 if self.id: diff --git a/apps/picture/tasks.py b/apps/picture/tasks.py index 1b4707694..fc9eafa7a 100644 --- a/apps/picture/tasks.py +++ b/apps/picture/tasks.py @@ -2,23 +2,18 @@ # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # -from datetime import datetime -from traceback import print_exc from celery.task import task -from django.conf import settings -import picture.models from django.core.files.base import ContentFile from django.template.loader import render_to_string -import librarian.picture @task def generate_picture_html(picture_id): + import picture.models pic = picture.models.Picture.objects.get(pk=picture_id) - html_text = unicode(render_to_string('picture/picture_info.html', { - 'things': pic.areas_json['things'], + 'things': pic.areas_json['things'], 'themes': pic.areas_json['themes'], })) pic.html_file.save("%s.html" % pic.slug, ContentFile(html_text)) diff --git a/apps/picture/templatetags/picture_tags.py b/apps/picture/templatetags/picture_tags.py index f0949a225..62826103b 100644 --- a/apps/picture/templatetags/picture_tags.py +++ b/apps/picture/templatetags/picture_tags.py @@ -3,12 +3,10 @@ # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django import template -from django.template import Node, Variable, Template, Context from catalogue.utils import split_tags -from itertools import chain from ..engine import CustomCroppingEngine import sorl.thumbnail.default -import logging +import logging register = template.Library() @@ -24,7 +22,7 @@ def picture_short(context, picture): 'tags': split_tags(picture.tags), }) return context - + @register.inclusion_tag('picture/picture_wide.html', takes_context=True) def picture_wide(context, picture): context.update({ @@ -51,7 +49,8 @@ def area_thumbnail_url(area, geometry): return [[coords[0][0], coords[0][1] + h/2 - w/2], [coords[1][0], coords[1][1] - h/2 + w/2, ]] - # so much for sorl extensibility. # what to do about this? + # so much for sorl extensibility. + # what to do about this? _engine = sorl.thumbnail.default.engine sorl.thumbnail.default.engine = cropper coords = to_square(area.area) @@ -68,7 +67,3 @@ def area_thumbnail_url(area, geometry): sorl.thumbnail.default.engine = _engine return th.url - - - - diff --git a/apps/picture/tests/picture_import.py b/apps/picture/tests/picture_import.py index e1bbd167e..84009e674 100644 --- a/apps/picture/tests/picture_import.py +++ b/apps/picture/tests/picture_import.py @@ -10,7 +10,7 @@ from catalogue.test_utils import WLTestCase class PictureTest(WLTestCase): - + def test_import(self): picture = Picture.from_xml_file(path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml")) @@ -24,7 +24,7 @@ class PictureTest(WLTestCase): path.join(path.dirname(__file__), "files/kandinsky-composition-viii.png")) picture.delete() - + def test_import_2(self): picture = Picture.from_xml_file(path.join(path.dirname(__file__), "files/pejzaz-i-miasto-krzyzanowski-chmury.xml"), diff --git a/apps/picture/views.py b/apps/picture/views.py index 3e471b0e8..832877e74 100644 --- a/apps/picture/views.py +++ b/apps/picture/views.py @@ -6,7 +6,6 @@ from django.contrib.auth.decorators import permission_required from django.utils.datastructures import SortedDict from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext -from django.core.paginator import Paginator from picture.models import Picture from catalogue.utils import split_tags @@ -59,7 +58,7 @@ def picture_viewer(request, slug): picture = get_object_or_404(Picture, slug=slug) return render_to_response("picture/picture_viewer.html", locals(), context_instance=RequestContext(request)) - + # ========= # = Admin = diff --git a/apps/polls/admin.py b/apps/polls/admin.py index 965f6c09b..235e8f3c2 100644 --- a/apps/polls/admin.py +++ b/apps/polls/admin.py @@ -4,22 +4,22 @@ # from django.contrib import admin -from models import Poll, PollItem +from .models import Poll, PollItem class PollItemInline(admin.TabularInline): model = PollItem extra = 0 readonly_fields = ('vote_count',) - - + + class PollAdmin(admin.ModelAdmin): inlines = [PollItemInline] - + class PollItemAdmin(admin.ModelAdmin): readonly_fields = ('vote_count',) - - + + admin.site.register(Poll, PollAdmin) admin.site.register(PollItem, PollItemAdmin) diff --git a/apps/polls/forms.py b/apps/polls/forms.py index fba346853..20d53fe33 100644 --- a/apps/polls/forms.py +++ b/apps/polls/forms.py @@ -6,8 +6,8 @@ from django import forms class PollForm(forms.Form): - vote = forms.ChoiceField(widget = forms.RadioSelect) - + vote = forms.ChoiceField(widget=forms.RadioSelect) + def __init__(self, *args, **kwargs): poll = kwargs.pop('poll', None) super(PollForm, self).__init__(*args, **kwargs) diff --git a/apps/polls/models.py b/apps/polls/models.py index 16713e479..f73b97043 100644 --- a/apps/polls/models.py +++ b/apps/polls/models.py @@ -15,48 +15,48 @@ class Poll(models.Model): question = models.TextField(_('question')) slug = models.SlugField(_('slug')) - open = models.BooleanField(_('open'), default = False) - + open = models.BooleanField(_('open'), default=False) + class Meta: verbose_name = _('Poll') verbose_name_plural = _('Polls') - + def clean(self): - if self.open and Poll.objects.exclude(pk = self.pk).filter(slug = self.slug).exists(): + if self.open and Poll.objects.exclude(pk=self.pk).filter(slug=self.slug).exists(): raise ValidationError(_('Slug of an open poll needs to be unique')) return super(Poll, self).clean() - + def __unicode__(self): return self.question[:100] + ' (' + self.slug + ')' - + def get_absolute_url(self): - return reverse('poll', args = [self.slug]) - + return reverse('poll', args=[self.slug]) + @property def vote_count(self): return self.items.all().aggregate(models.Sum('vote_count'))['vote_count__sum'] - + def voted(self, session): return self.id in session.get(USED_POLLS_KEY, set()) - + class PollItem(models.Model): - - poll = models.ForeignKey(Poll, related_name = 'items') + + poll = models.ForeignKey(Poll, related_name='items') content = models.TextField(_('content')) - vote_count = models.IntegerField(_('vote count'), default = 0) - + vote_count = models.IntegerField(_('vote count'), default=0) + class Meta: verbose_name = _('vote item') verbose_name_plural = _('vote items') - + def __unicode__(self): return self.content + ' @ ' + unicode(self.poll) - + @property def vote_ratio(self): return (float(self.vote_count) / self.poll.vote_count) * 100 if self.poll.vote_count else 0 - + def vote(self, session): self.vote_count = self.vote_count + 1 self.save() diff --git a/apps/polls/templatetags/polls_tags.py b/apps/polls/templatetags/polls_tags.py index d17d30956..fffa78056 100644 --- a/apps/polls/templatetags/polls_tags.py +++ b/apps/polls/templatetags/polls_tags.py @@ -8,15 +8,15 @@ from ..forms import PollForm register = template.Library() -@register.inclusion_tag('polls/tags/poll.html', takes_context = True) -def poll(context, poll, show_results = True, redirect_to = ''): +@register.inclusion_tag('polls/tags/poll.html', takes_context=True) +def poll(context, poll, show_results=True, redirect_to=''): form = None voted_already = poll.voted(context.get('request').session) if not voted_already: - form = PollForm(poll = poll, initial = dict(redirect_to = redirect_to)) - return dict(poll = poll, - form = form, - voted_already = voted_already, - vote_count = poll.vote_count, - show_results = show_results + form = PollForm(poll=poll, initial=dict(redirect_to=redirect_to)) + return dict(poll=poll, + form=form, + voted_already=voted_already, + vote_count=poll.vote_count, + show_results=show_results ) diff --git a/apps/polls/views.py b/apps/polls/views.py index 1dcd38767..ef5f50f5e 100644 --- a/apps/polls/views.py +++ b/apps/polls/views.py @@ -7,22 +7,22 @@ from django.shortcuts import get_object_or_404, redirect, render_to_response from django.core.urlresolvers import reverse from django.template import RequestContext -from models import Poll, PollItem -from forms import PollForm +from .models import Poll, PollItem +from .forms import PollForm @require_http_methods(['GET', 'POST']) def poll(request, slug): - - poll = get_object_or_404(Poll, slug = slug, open = True) - + + poll = get_object_or_404(Poll, slug=slug, open=True) + if request.method == 'POST': redirect_to = reverse('poll', args = [slug]) form = PollForm(request.POST, poll = poll) if form.is_valid(): if not poll.voted(request.session): try: - poll_item = PollItem.objects.filter(pk = form.cleaned_data['vote'], poll = poll).get() + poll_item = PollItem.objects.filter(pk=form.cleaned_data['vote'], poll=poll).get() except PollItem.DoesNotExist: pass else: @@ -33,6 +33,3 @@ def poll(request, slug): context['poll'] = poll context['voted_already'] = poll.voted(request.session) return render_to_response('polls/poll.html', context) - - - diff --git a/apps/reporting/templatetags/reporting_stats.py b/apps/reporting/templatetags/reporting_stats.py index ee9a7bf74..7bbe23d03 100755 --- a/apps/reporting/templatetags/reporting_stats.py +++ b/apps/reporting/templatetags/reporting_stats.py @@ -2,13 +2,9 @@ # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # -import feedparser from functools import wraps -import datetime - from django import template - -from catalogue.models import Book, BookMedia +from catalogue.models import Book register = template.Library() diff --git a/apps/reporting/utils.py b/apps/reporting/utils.py index a8a6bb1dd..06a168074 100755 --- a/apps/reporting/utils.py +++ b/apps/reporting/utils.py @@ -30,7 +30,7 @@ def render_to_pdf(output_path, template, context=None, add_files=None): rendered = render_to_string(template, context) texml = StringIO(rendered.encode('utf-8')) - tempdir = mkdtemp(prefix = "render_to_pdf-") + tempdir = mkdtemp(prefix="render_to_pdf-") tex_path = os.path.join(tempdir, "doc.tex") with open(tex_path, 'w') as tex_file: Texml.processor.process(texml, tex_file, encoding="utf-8") @@ -69,7 +69,7 @@ def render_to_csv(output_path, template, context=None, add_files=None): """ from django.template.loader import render_to_string - + try: os.makedirs(os.path.dirname(output_path)) except: @@ -78,7 +78,7 @@ def render_to_csv(output_path, template, context=None, add_files=None): rendered = render_to_string(template, context) with open(output_path, 'w') as csv_file: csv_file.write(rendered.encode('utf-8')) - + def read_chunks(f, size=8192): chunk = f.read(size) @@ -89,7 +89,6 @@ def read_chunks(f, size=8192): def generated_file_view(file_name, mime_type, send_name=None, signals=None): file_path = os.path.join(settings.MEDIA_ROOT, file_name) - file_url = os.path.join(settings.MEDIA_URL, file_name) if send_name is None: send_name = os.path.basename(file_name) diff --git a/apps/reporting/views.py b/apps/reporting/views.py index a23252ec2..8cb2715d5 100644 --- a/apps/reporting/views.py +++ b/apps/reporting/views.py @@ -37,7 +37,7 @@ def stats_page(request): locals(), context_instance=RequestContext(request)) -@generated_file_view('reports/katalog.pdf', 'application/pdf', +@generated_file_view('reports/katalog.pdf', 'application/pdf', send_name=lambda: 'wolnelektury_%s.pdf' % date.today(), signals=[Book.published]) def catalogue_pdf(path): @@ -47,7 +47,7 @@ def catalogue_pdf(path): }) -@generated_file_view('reports/katalog.csv', 'application/csv', +@generated_file_view('reports/katalog.csv', 'application/csv', send_name=lambda: 'wolnelektury_%s.csv' % date.today(), signals=[Book.published]) def catalogue_csv(path): diff --git a/apps/social/templatetags/social_tags.py b/apps/social/templatetags/social_tags.py index d6d3f7110..ecf2c668c 100755 --- a/apps/social/templatetags/social_tags.py +++ b/apps/social/templatetags/social_tags.py @@ -21,7 +21,7 @@ def choose_cite(context, ctx=None): assert request.user.is_staff assert 'choose_cite' in request.GET cite = Cite.objects.get(pk=request.GET['choose_cite']) - except AssertionError, Cite.DoesNotExist: + except (AssertionError, Cite.DoesNotExist): if ctx is None: cites = Cite.objects.all() elif isinstance(ctx, Book): diff --git a/apps/social/urls.py b/apps/social/urls.py index 657b29713..b25ab2509 100755 --- a/apps/social/urls.py +++ b/apps/social/urls.py @@ -17,4 +17,4 @@ urlpatterns = patterns('social.views', #~ url(r'^polki/(?P[a-zA-Z0-9-]+)/usun/$', 'delete_shelf', name='delete_shelf'), #~ url(r'^polki/(?P[a-zA-Z0-9-]+)\.zip$', 'download_shelf', name='download_shelf'), #~ url(r'^polki/nowa/$', 'new_set', name='new_set'), -) +) diff --git a/apps/social/views.py b/apps/social/views.py index 8af17da4f..e5a827055 100644 --- a/apps/social/views.py +++ b/apps/social/views.py @@ -5,15 +5,11 @@ from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponseForbidden from django.contrib.auth.decorators import login_required -#~ from django.utils.datastructures import SortedDict from django.views.decorators.http import require_POST -#~ from django.contrib import auth -#~ from django.views.decorators import cache -from django.utils.translation import ugettext as _ -from ajaxable.utils import LazyEncoder, JSONResponse, AjaxableFormView +from ajaxable.utils import JSONResponse, AjaxableFormView -from catalogue.models import Book, Tag +from catalogue.models import Book from social import forms from social.utils import get_set, likes, set_sets diff --git a/apps/sponsors/models.py b/apps/sponsors/models.py index cbc8d9ba4..fd3c3a925 100644 --- a/apps/sponsors/models.py +++ b/apps/sponsors/models.py @@ -64,7 +64,7 @@ class SponsorPage(models.Model): simg = Image.open(sponsors[sponsor_id].logo.path) if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT: size = ( - min(THUMB_WIDTH, + min(THUMB_WIDTH, simg.size[0] * THUMB_HEIGHT / simg.size[1]), min(THUMB_HEIGHT, simg.size[1] * THUMB_WIDTH / simg.size[0]) diff --git a/apps/stats/utils.py b/apps/stats/utils.py index 921921d4c..543f86341 100644 --- a/apps/stats/utils.py +++ b/apps/stats/utils.py @@ -2,7 +2,6 @@ # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # -from django.contrib.sites.models import Site from django.conf import settings from datetime import datetime import logging diff --git a/apps/waiter/models.py b/apps/waiter/models.py index 8b6ff94e5..e64e4dbba 100644 --- a/apps/waiter/models.py +++ b/apps/waiter/models.py @@ -19,7 +19,7 @@ class WaitedFile(models.Model): @classmethod def exists(cls, path): """Returns opened file or None. - + `path` is relative to WAITER_ROOT. Won't open a path leading outside of WAITER_ROOT. """ @@ -41,7 +41,7 @@ class WaitedFile(models.Model): def is_stale(self): if self.task is None: - # Race; just let the other task roll. + # Race; just let the other task roll. return False if self.task.status not in (u'PENDING', u'STARTED', u'SUCCESS', u'RETRY'): return True diff --git a/apps/waiter/utils.py b/apps/waiter/utils.py index 1edc2faa1..68d21bd79 100644 --- a/apps/waiter/utils.py +++ b/apps/waiter/utils.py @@ -18,4 +18,3 @@ def clear_cache(path): abs_path = check_abspath(path) if exists(abs_path): rmtree(abs_path) - diff --git a/apps/wolnelektury_core/management/commands/localepack.py b/apps/wolnelektury_core/management/commands/localepack.py index 3c1a710d8..bd631928c 100644 --- a/apps/wolnelektury_core/management/commands/localepack.py +++ b/apps/wolnelektury_core/management/commands/localepack.py @@ -12,7 +12,6 @@ import os import shutil import tempfile import sys -import zipfile import allauth @@ -34,7 +33,7 @@ def copy_f(frm, to): "I can create a necessary dest directiories, yey!" if not os.path.exists(os.path.dirname(to)): os.makedirs(os.path.dirname(to)) - shutil.copyfile(frm,to) + shutil.copyfile(frm, to) class AppLocale(Locale): def __init__(self, appmod): @@ -215,7 +214,7 @@ class Command(BaseCommand): if not options['directory'] or not os.path.exists(options['directory']): print "Directory not provided or does not exist, please use -d" sys.exit(1) - + if options['merge']: self.merge_setup(options['directory']) self.load(options) if options['merge']: self.merge_finish(options['message']) @@ -224,7 +223,7 @@ class Command(BaseCommand): merge_branch = 'wl-locale-merge' last_branch = None - + def merge_setup(self, directory): self.last_branch = self.current_branch() rev = open(os.path.join(directory, '.revision')).read() diff --git a/apps/wolnelektury_core/management/commands/translation2po.py b/apps/wolnelektury_core/management/commands/translation2po.py index 02a1d0868..6220006fe 100644 --- a/apps/wolnelektury_core/management/commands/translation2po.py +++ b/apps/wolnelektury_core/management/commands/translation2po.py @@ -3,7 +3,6 @@ # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # import os -import sys import time from optparse import make_option from django.conf import settings @@ -90,7 +89,7 @@ class Command(BaseCommand): for lng in zip(*languages)[0]: pofile = os.path.join(options['directory'], lng, options['poname'] + '.po') - if not os.path.exists(pofile): + if not os.path.exists(pofile): if options['keep_running']: continue else: