moviewyrm/bookwyrm/views/books/links.py

63 lines
2.1 KiB
Python
Raw Normal View History

2021-12-15 21:15:51 +00:00
""" the good stuff! the books! """
from django.contrib.auth.decorators import login_required, permission_required
from django.db import transaction
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.views import View
from django.utils.decorators import method_decorator
from bookwyrm import forms, models
# pylint: disable=no-self-use
2022-01-12 17:52:26 +00:00
class BookFileLinks(View):
"""View all links"""
def get(self, request, book_id):
"""view links"""
book = get_object_or_404(models.Edition, id=book_id)
2022-01-13 01:11:24 +00:00
return TemplateResponse(
request, "book/file_links/edit_links.html", {"book": book}
)
2022-01-12 17:52:26 +00:00
2022-01-12 18:07:49 +00:00
def post(self, request, book_id, link_id):
"""delete link"""
link = get_object_or_404(models.FileLink, id=link_id, book=book_id)
link.delete()
return self.get(request, book_id)
2022-01-12 17:52:26 +00:00
2021-12-15 21:15:51 +00:00
@method_decorator(login_required, name="dispatch")
@method_decorator(
permission_required("bookwyrm.edit_book", raise_exception=True), name="dispatch"
)
2022-01-12 17:16:24 +00:00
class AddFileLink(View):
2021-12-15 21:15:51 +00:00
"""a book! this is the stuff"""
2022-01-12 17:16:24 +00:00
def get(self, request, book_id):
"""Create link form"""
2021-12-16 00:23:21 +00:00
book = get_object_or_404(models.Edition, id=book_id)
2021-12-15 21:15:51 +00:00
data = {
2022-01-12 17:16:24 +00:00
"file_link_form": forms.FileLinkForm(),
2021-12-15 21:15:51 +00:00
"book": book,
}
2022-01-13 00:46:14 +00:00
return TemplateResponse(request, "book/file_links/file_link_page.html", data)
2021-12-15 21:15:51 +00:00
@transaction.atomic
2021-12-15 21:20:05 +00:00
def post(self, request, book_id, link_id=None):
2021-12-15 21:15:51 +00:00
"""Add a link to a copy of the book you can read"""
book = get_object_or_404(models.Book.objects.select_subclasses(), id=book_id)
2021-12-15 21:20:05 +00:00
link = get_object_or_404(models.FileLink, id=link_id) if link_id else None
form = forms.FileLinkForm(request.POST, instance=link)
2021-12-15 21:15:51 +00:00
if not form.is_valid():
data = {"file_link_form": form, "book": book}
2022-01-13 01:11:24 +00:00
return TemplateResponse(
request, "book/file_links/file_link_page.html", data
)
2021-12-15 21:15:51 +00:00
link = form.save()
book.file_links.add(link)
book.last_edited_by = request.user
book.save()
return redirect("book", book.id)