Add missing constraint.
[wolnelektury.git] / src / lesmianator / views.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import json
5 from django.shortcuts import render, get_object_or_404
6 from django.views.decorators import cache
7
8 from catalogue.utils import get_random_hash
9 from catalogue.models import Book, Tag
10 from lesmianator.models import Poem, Continuations
11
12
13 def main_page(request):
14     last = Poem.objects.all().order_by('-created_at')[:10]
15     shelves = Tag.objects.filter(user__username='lesmianator')
16
17     return render(
18         request,
19         'lesmianator/2022/lesmianator.html' if request.EXPERIMENTS['layout'].value else 'lesmianator/lesmianator.html',
20         {"last": last, "shelves": shelves})
21
22 @cache.never_cache
23 def new_poem(request):
24     user = request.user if request.user.is_authenticated else None
25     text = Poem.write()
26     p = Poem(slug=get_random_hash(text), text=text, created_by=user)
27     p.save()
28
29     return render(
30         request,
31         'lesmianator/poem.html',
32         {"poem": p})
33
34
35 @cache.never_cache
36 def poem_from_book(request, slug):
37     book = get_object_or_404(Book, slug=slug)
38     user = request.user if request.user.is_authenticated else None
39     text = Poem.write(Continuations.get(book))
40     p = Poem(slug=get_random_hash(text), text=text, created_by=user)
41     p.created_from = json.dumps([book.id])
42     p.save()
43
44     return render(
45         request,
46         'lesmianator/poem.html',
47         {"poem": p, "books": [book], "book": book})
48
49
50 @cache.never_cache
51 def poem_from_set(request, shelf):
52     user = request.user if request.user.is_authenticated else None
53     tag = get_object_or_404(Tag, category='set', slug=shelf)
54     text = Poem.write(Continuations.get(tag))
55     p = Poem(slug=get_random_hash(text), text=text, created_by=user)
56     books = Book.tagged.with_any((tag,))
57     p.created_from = json.dumps([b.id for b in books])
58     p.save()
59
60     book = books[0] if len(books) == 1 else None
61
62     return render(
63         request,
64         'lesmianator/poem.html',
65         {"poem": p, "shelf": tag, "books": books, "book": book})
66
67
68 def get_poem(request, poem):
69     p = get_object_or_404(Poem, slug=poem)
70     p.visit()
71     created_from = json.loads(p.created_from or '[]')
72     if created_from:
73         books = Book.objects.filter(id__in=created_from)
74         book = books[0] if len(books) == 1 else None
75     else:
76         books = book = None
77
78     return render(
79         request,
80         'lesmianator/poem.html',
81         {"poem": p, "books": books, "book": book})