1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
7 from datetime import datetime
9 from django.conf import settings
10 from django.template import RequestContext
11 from django.shortcuts import render_to_response, get_object_or_404
12 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
13 from django.core.urlresolvers import reverse
14 from django.db.models import Count, Sum, Q
15 from django.contrib.auth.decorators import login_required, user_passes_test
16 from django.utils.datastructures import SortedDict
17 from django.views.decorators.http import require_POST
18 from django.contrib import auth
19 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
20 from django.utils import simplejson
21 from django.utils.functional import Promise
22 from django.utils.encoding import force_unicode
23 from django.utils.http import urlquote_plus
24 from django.views.decorators import cache
25 from django.utils import translation
26 from django.utils.translation import ugettext as _
27 from django.views.generic.list_detail import object_list
29 from catalogue import models
30 from catalogue import forms
31 from catalogue.utils import split_tags, AttachmentHttpResponse, create_custom_pdf
32 from pdcounter import models as pdcounter_models
33 from pdcounter import views as pdcounter_views
34 from suggest.forms import PublishingSuggestForm
38 staff_required = user_passes_test(lambda user: user.is_staff)
41 class LazyEncoder(simplejson.JSONEncoder):
42 def default(self, obj):
43 if isinstance(obj, Promise):
44 return force_unicode(obj)
47 # shortcut for JSON reponses
48 class JSONResponse(HttpResponse):
49 def __init__(self, data={}, callback=None, **kwargs):
51 kwargs.pop('mimetype', None)
52 data = simplejson.dumps(data)
54 data = callback + "(" + data + ");"
55 super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
58 def main_page(request):
59 if request.user.is_authenticated():
60 shelves = models.Tag.objects.filter(category='set', user=request.user)
61 new_set_form = forms.NewSetForm()
63 tags = models.Tag.objects.exclude(category__in=('set', 'book'))
65 tag.count = tag.get_count()
66 categories = split_tags(tags)
67 fragment_tags = categories.get('theme', [])
69 form = forms.SearchForm()
70 return render_to_response('catalogue/main_page.html', locals(),
71 context_instance=RequestContext(request))
74 def book_list(request, filter=None, template_name='catalogue/book_list.html'):
75 """ generates a listing of all books, optionally filtered with a test function """
77 form = forms.SearchForm()
79 books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
80 books_nav = SortedDict()
81 for tag in books_by_author:
82 if books_by_author[tag]:
83 books_nav.setdefault(tag.sort_key[0], []).append(tag)
85 return render_to_response(template_name, locals(),
86 context_instance=RequestContext(request))
89 def audiobook_list(request):
90 return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
91 template_name='catalogue/audiobook_list.html')
94 def daisy_list(request):
95 return book_list(request, Q(media__type='daisy'),
96 template_name='catalogue/daisy_list.html')
99 def differentiate_tags(request, tags, ambiguous_slugs):
100 beginning = '/'.join(tag.url_chunk for tag in tags)
101 unparsed = '/'.join(ambiguous_slugs[1:])
103 for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
105 'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
108 return render_to_response('catalogue/differentiate_tags.html',
109 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
110 context_instance=RequestContext(request))
113 def tagged_object_list(request, tags=''):
115 tags = models.Tag.get_tag_list(tags)
116 except models.Tag.DoesNotExist:
117 chunks = tags.split('/')
118 if len(chunks) == 2 and chunks[0] == 'autor':
119 return pdcounter_views.author_detail(request, chunks[1])
122 except models.Tag.MultipleObjectsReturned, e:
123 return differentiate_tags(request, e.tags, e.ambiguous_slugs)
124 except models.Tag.UrlDeprecationWarning, e:
125 return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
128 if len(tags) > settings.MAX_TAG_LIST:
130 except AttributeError:
133 if len([tag for tag in tags if tag.category == 'book']):
136 theme_is_set = [tag for tag in tags if tag.category == 'theme']
137 shelf_is_set = [tag for tag in tags if tag.category == 'set']
138 only_shelf = shelf_is_set and len(tags) == 1
139 only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
141 objects = only_author = None
145 shelf_tags = [tag for tag in tags if tag.category == 'set']
146 fragment_tags = [tag for tag in tags if tag.category != 'set']
147 fragments = models.Fragment.tagged.with_all(fragment_tags)
150 books = models.Book.tagged.with_all(shelf_tags).order_by()
151 l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in books])
152 fragments = models.Fragment.tagged.with_any(l_tags, fragments)
154 # newtagging goes crazy if we just try:
155 #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
156 # extra={'where': ["catalogue_tag.category != 'book'"]})
157 fragment_keys = [fragment.pk for fragment in fragments]
159 related_tags = models.Fragment.tags.usage(counts=True,
160 filters={'pk__in': fragment_keys},
161 extra={'where': ["catalogue_tag.category != 'book'"]})
162 related_tags = (tag for tag in related_tags if tag not in fragment_tags)
163 categories = split_tags(related_tags)
168 objects = models.Book.tagged.with_all(tags)
170 objects = models.Book.tagged_top_level(tags)
172 # get related tags from `tag_counter` and `theme_counter`
174 tags_pks = [tag.pk for tag in tags]
176 for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
177 if tag_pk in tags_pks:
179 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
180 related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
181 related_tags = [tag for tag in related_tags if tag not in tags]
182 for tag in related_tags:
183 tag.count = related_counts[tag.pk]
185 categories = split_tags(related_tags)
189 only_author = len(tags) == 1 and tags[0].category == 'author'
190 objects = models.Book.objects.none()
195 template_name='catalogue/tagged_object_list.html',
197 'categories': categories,
198 'only_shelf': only_shelf,
199 'only_author': only_author,
200 'only_my_shelf': only_my_shelf,
201 'formats_form': forms.DownloadFormatsForm(),
207 def book_fragments(request, book_slug, theme_slug):
208 book = get_object_or_404(models.Book, slug=book_slug)
209 book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug, category='book')
210 theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
211 fragments = models.Fragment.tagged.with_all([book_tag, theme])
213 form = forms.SearchForm()
214 return render_to_response('catalogue/book_fragments.html', locals(),
215 context_instance=RequestContext(request))
218 def book_detail(request, slug):
220 book = models.Book.objects.get(slug=slug)
221 except models.Book.DoesNotExist:
222 return pdcounter_views.book_stub_detail(request, slug)
224 book_tag = book.book_tag()
225 tags = list(book.tags.filter(~Q(category='set')))
226 categories = split_tags(tags)
227 book_children = book.children.all().order_by('parent_number', 'sort_key')
232 parents.append(_book.parent)
234 parents = reversed(parents)
236 theme_counter = book.theme_counter
237 book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
238 for tag in book_themes:
239 tag.count = theme_counter[tag.pk]
241 extra_info = book.get_extra_info_value()
242 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
245 for m in book.media.filter(type='mp3'):
246 # ogg files are always from the same project
247 meta = m.get_extra_info_value()
248 project = meta.get('project')
251 project = u'CzytamySłuchając'
253 projects.add((project, meta.get('funded_by', '')))
254 projects = sorted(projects)
256 form = forms.SearchForm()
257 custom_pdf_form = forms.CustomPDFForm()
258 return render_to_response('catalogue/book_detail.html', locals(),
259 context_instance=RequestContext(request))
262 def book_text(request, slug):
263 book = get_object_or_404(models.Book, slug=slug)
264 if not book.has_html_file():
267 for fragment in book.fragments.all():
268 for theme in fragment.tags.filter(category='theme'):
269 book_themes.setdefault(theme, []).append(fragment)
271 book_themes = book_themes.items()
272 book_themes.sort(key=lambda s: s[0].sort_key)
273 return render_to_response('catalogue/book_text.html', locals(),
274 context_instance=RequestContext(request))
281 def _no_diacritics_regexp(query):
282 """ returns a regexp for searching for a query without diacritics
284 should be locale-aware """
286 u'a':u'aąĄ', u'c':u'cćĆ', u'e':u'eęĘ', u'l': u'lłŁ', u'n':u'nńŃ', u'o':u'oóÓ', u's':u'sśŚ', u'z':u'zźżŹŻ',
287 u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
291 return u"(%s)" % '|'.join(names[l])
292 return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
294 def unicode_re_escape(query):
295 """ Unicode-friendly version of re.escape """
296 return re.sub('(?u)(\W)', r'\\\1', query)
298 def _word_starts_with(name, prefix):
299 """returns a Q object getting models having `name` contain a word
300 starting with `prefix`
302 We define word characters as alphanumeric and underscore, like in JS.
304 Works for MySQL, PostgreSQL, Oracle.
305 For SQLite, _sqlite* version is substituted for this.
309 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
310 # can't use [[:<:]] (word start),
311 # but we want both `xy` and `(xy` to catch `(xyz)`
312 kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
317 def _word_starts_with_regexp(prefix):
318 prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
319 return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
322 def _sqlite_word_starts_with(name, prefix):
323 """ version of _word_starts_with for SQLite
325 SQLite in Django uses Python re module
328 kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
332 if hasattr(settings, 'DATABASES'):
333 if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
334 _word_starts_with = _sqlite_word_starts_with
335 elif settings.DATABASE_ENGINE == 'sqlite3':
336 _word_starts_with = _sqlite_word_starts_with
340 def __init__(self, name, view):
343 self.lower = name.lower()
344 self.category = 'application'
346 return reverse(*self._view)
349 App(u'Leśmianator', (u'lesmianator', )),
353 def _tags_starting_with(prefix, user=None):
354 prefix = prefix.lower()
356 book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
357 authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
359 books = models.Book.objects.filter(_word_starts_with('title', prefix))
360 tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
361 if user and user.is_authenticated():
362 tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
364 tags = tags.filter(~Q(category='book') & ~Q(category='set'))
366 prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
367 return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
370 def _get_result_link(match, tag_list):
371 if isinstance(match, models.Tag):
372 return reverse('catalogue.views.tagged_object_list',
373 kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
375 elif isinstance(match, App):
378 return match.get_absolute_url()
381 def _get_result_type(match):
382 if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
385 type = match.category
389 def books_starting_with(prefix):
390 prefix = prefix.lower()
391 return models.Book.objects.filter(_word_starts_with('title', prefix))
394 def find_best_matches(query, user=None):
395 """ Finds a Book, Tag, BookStub or Author best matching a query.
398 - zero elements when nothing is found,
399 - one element when a best result is found,
400 - more then one element on multiple exact matches
402 Raises a ValueError on too short a query.
405 query = query.lower()
407 raise ValueError("query must have at least two characters")
409 result = tuple(_tags_starting_with(query, user))
410 # remove pdcounter stuff
411 book_titles = set(match.pretty_title().lower() for match in result
412 if isinstance(match, models.Book))
413 authors = set(match.name.lower() for match in result
414 if isinstance(match, models.Tag) and match.category=='author')
415 result = tuple(res for res in result if not (
416 (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
417 or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
420 exact_matches = tuple(res for res in result if res.name.lower() == query)
424 return tuple(result)[:1]
428 tags = request.GET.get('tags', '')
429 prefix = request.GET.get('q', '')
432 tag_list = models.Tag.get_tag_list(tags)
437 result = find_best_matches(prefix, request.user)
439 return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
440 context_instance=RequestContext(request))
443 return HttpResponseRedirect(_get_result_link(result[0], tag_list))
444 elif len(result) > 1:
445 return render_to_response('catalogue/search_multiple_hits.html',
446 {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
447 context_instance=RequestContext(request))
449 form = PublishingSuggestForm(initial={"books": prefix + ", "})
450 return render_to_response('catalogue/search_no_hits.html',
451 {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
452 context_instance=RequestContext(request))
455 def tags_starting_with(request):
456 prefix = request.GET.get('q', '')
457 # Prefix must have at least 2 characters
459 return HttpResponse('')
462 for tag in _tags_starting_with(prefix, request.user):
463 if not tag.name in tags_list:
464 result += "\n" + tag.name
465 tags_list.append(tag.name)
466 return HttpResponse(result)
468 def json_tags_starting_with(request, callback=None):
470 prefix = request.GET.get('q', '')
471 callback = request.GET.get('callback', '')
472 # Prefix must have at least 2 characters
474 return HttpResponse('')
476 for tag in _tags_starting_with(prefix, request.user):
477 if not tag.name in tags_list:
478 tags_list.append(tag.name)
479 if request.GET.get('mozhint', ''):
480 result = [prefix, tags_list]
482 result = {"matches": tags_list}
483 return JSONResponse(result, callback)
485 # ====================
486 # = Shelf management =
487 # ====================
490 def user_shelves(request):
491 shelves = models.Tag.objects.filter(category='set', user=request.user)
492 new_set_form = forms.NewSetForm()
493 return render_to_response('catalogue/user_shelves.html', locals(),
494 context_instance=RequestContext(request))
497 def book_sets(request, slug):
498 if not request.user.is_authenticated():
499 return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
501 book = get_object_or_404(models.Book, slug=slug)
502 user_sets = models.Tag.objects.filter(category='set', user=request.user)
503 book_sets = book.tags.filter(category='set', user=request.user)
505 if request.method == 'POST':
506 form = forms.ObjectSetsForm(book, request.user, request.POST)
508 old_shelves = list(book.tags.filter(category='set'))
509 new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
511 for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
512 shelf.book_count = None
515 for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
516 shelf.book_count = None
519 book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
520 if request.is_ajax():
521 return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
523 return HttpResponseRedirect('/')
525 form = forms.ObjectSetsForm(book, request.user)
526 new_set_form = forms.NewSetForm()
528 return render_to_response('catalogue/book_sets.html', locals(),
529 context_instance=RequestContext(request))
535 def remove_from_shelf(request, shelf, book):
536 book = get_object_or_404(models.Book, slug=book)
537 shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
539 if shelf in book.tags:
540 models.Tag.objects.remove_tag(book, shelf)
542 shelf.book_count = None
545 return HttpResponse(_('Book was successfully removed from the shelf'))
547 return HttpResponse(_('This book is not on the shelf'))
550 def collect_books(books):
552 Returns all real books in collection.
556 if len(book.children.all()) == 0:
559 result += collect_books(book.children.all())
564 def download_shelf(request, slug):
566 Create a ZIP archive on disk and transmit it in chunks of 8KB,
567 without loading the whole file into memory. A similar approach can
568 be used for large dynamic PDF files.
570 from slughifi import slughifi
574 shelf = get_object_or_404(models.Tag, slug=slug, category='set')
577 form = forms.DownloadFormatsForm(request.GET)
579 formats = form.cleaned_data['formats']
580 if len(formats) == 0:
581 formats = ['pdf', 'epub', 'mobi', 'odt', 'txt']
583 # Create a ZIP archive
584 temp = tempfile.TemporaryFile()
585 archive = zipfile.ZipFile(temp, 'w')
588 for book in collect_books(models.Book.tagged.with_all(shelf)):
589 if 'pdf' in formats and book.pdf_file:
590 filename = book.pdf_file.path
591 archive.write(filename, str('%s.pdf' % book.slug))
592 if 'mobi' in formats and book.mobi_file:
593 filename = book.mobi_file.path
594 archive.write(filename, str('%s.mobi' % book.slug))
595 if book.root_ancestor not in already and 'epub' in formats and book.root_ancestor.epub_file:
596 filename = book.root_ancestor.epub_file.path
597 archive.write(filename, str('%s.epub' % book.root_ancestor.slug))
598 already.add(book.root_ancestor)
599 if 'odt' in formats and book.has_media("odt"):
600 for file in book.get_media("odt"):
601 filename = file.file.path
602 archive.write(filename, str('%s.odt' % slughifi(file.name)))
603 if 'txt' in formats and book.txt_file:
604 filename = book.txt_file.path
605 archive.write(filename, str('%s.txt' % book.slug))
608 response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
609 response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
610 response['Content-Length'] = temp.tell()
613 response.write(temp.read())
618 def shelf_book_formats(request, shelf):
620 Returns a list of formats of books in shelf.
622 shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
624 formats = {'pdf': False, 'epub': False, 'mobi': False, 'odt': False, 'txt': False}
626 for book in collect_books(models.Book.tagged.with_all(shelf)):
628 formats['pdf'] = True
629 if book.root_ancestor.epub_file:
630 formats['epub'] = True
632 formats['mobi'] = True
634 formats['txt'] = True
635 for format in ('odt',):
636 if book.has_media(format):
637 formats[format] = True
639 return HttpResponse(LazyEncoder().encode(formats))
645 def new_set(request):
646 new_set_form = forms.NewSetForm(request.POST)
647 if new_set_form.is_valid():
648 new_set = new_set_form.save(request.user)
650 if request.is_ajax():
651 return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
653 return HttpResponseRedirect('/')
655 return HttpResponseRedirect('/')
661 def delete_shelf(request, slug):
662 user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
665 if request.is_ajax():
666 return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
668 return HttpResponseRedirect('/')
677 form = AuthenticationForm(data=request.POST, prefix='login')
679 auth.login(request, form.get_user())
680 response_data = {'success': True, 'errors': {}}
682 response_data = {'success': False, 'errors': form.errors}
683 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
688 def register(request):
689 registration_form = UserCreationForm(request.POST, prefix='registration')
690 if registration_form.is_valid():
691 user = registration_form.save()
692 user = auth.authenticate(
693 username=registration_form.cleaned_data['username'],
694 password=registration_form.cleaned_data['password1']
696 auth.login(request, user)
697 response_data = {'success': True, 'errors': {}}
699 response_data = {'success': False, 'errors': registration_form.errors}
700 return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
704 def logout_then_redirect(request):
706 return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
715 def import_book(request):
716 """docstring for import_book"""
717 book_import_form = forms.BookImportForm(request.POST, request.FILES)
718 if book_import_form.is_valid():
720 book_import_form.save()
725 info = sys.exc_info()
726 exception = pprint.pformat(info[1])
727 tb = '\n'.join(traceback.format_tb(info[2]))
728 return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
729 return HttpResponse(_("Book imported successfully"))
731 return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
736 """ Provides server time for jquery.countdown,
737 in a format suitable for Date.parse()
739 return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
744 def book_info(request, id, lang='pl'):
745 book = get_object_or_404(models.Book, id=id)
746 # set language by hand
747 translation.activate(lang)
748 return render_to_response('catalogue/book_info.html', locals(),
749 context_instance=RequestContext(request))
752 def tag_info(request, id):
753 tag = get_object_or_404(models.Tag, id=id)
754 return HttpResponse(tag.description)
757 def download_zip(request, format, slug):
759 if format in ('pdf', 'epub', 'mobi'):
760 url = models.Book.zip_format(format)
761 elif format == 'audiobook' and slug is not None:
762 book = models.Book.objects.get(slug=slug)
763 url = book.zip_audiobooks()
765 raise Http404('No format specified for zip package')
766 return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
769 def download_custom_pdf(request, slug):
770 book = models.Book.objects.get(slug=slug)
771 if request.method == 'GET':
772 form = forms.CustomPDFForm(request.GET)
774 cust = form.customizations
775 h = hash(tuple(cust))
776 pdf_name = '%s-custom-%s' % (book.slug, h)
777 pdf_file = path.join(settings.MEDIA_ROOT, models.get_dynamic_path(None, pdf_name, ext='pdf'))
779 if not path.exists(pdf_file):
780 result = create_custom_pdf.delay(book.id, cust, pdf_name)
782 return AttachmentHttpResponse(file_name=("%s.pdf" % book.slug), file_path=pdf_file, mimetype="application/pdf")
784 raise Http404(_('Incorrect customization options for PDF'))
786 raise Http404(_('Bad method'))