moviewyrm/bookwyrm/views/tag.py

74 lines
2.2 KiB
Python
Raw Normal View History

2021-03-08 16:49:10 +00:00
""" tagging views"""
2021-01-13 18:24:24 +00:00
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.views import View
from bookwyrm import models
from bookwyrm.activitypub import ActivitypubResponse
from .helpers import is_api_request
# pylint: disable= no-self-use
class Tag(View):
2021-03-08 16:49:10 +00:00
""" tag page """
2021-01-13 18:24:24 +00:00
def get(self, request, tag_id):
2021-03-08 16:49:10 +00:00
""" see books related to a tag """
2021-02-24 01:18:25 +00:00
tag_obj = get_object_or_404(models.Tag, identifier=tag_id)
2021-01-13 18:24:24 +00:00
if is_api_request(request):
2021-03-08 16:49:10 +00:00
return ActivitypubResponse(tag_obj.to_activity(**request.GET))
2021-01-13 18:24:24 +00:00
books = models.Edition.objects.filter(
usertag__tag__identifier=tag_id
).distinct()
data = {
2021-03-08 16:49:10 +00:00
"books": books,
"tag": tag_obj,
2021-01-13 18:24:24 +00:00
}
2021-03-08 16:49:10 +00:00
return TemplateResponse(request, "tag.html", data)
2021-01-13 18:24:24 +00:00
2021-03-08 16:49:10 +00:00
@method_decorator(login_required, name="dispatch")
2021-01-13 18:24:24 +00:00
class AddTag(View):
2021-03-08 16:49:10 +00:00
""" add a tag to a book """
2021-01-13 18:24:24 +00:00
def post(self, request):
2021-03-08 16:49:10 +00:00
""" tag a book """
2021-01-13 18:24:24 +00:00
# I'm not using a form here because sometimes "name" is sent as a hidden
# field which doesn't validate
2021-03-08 16:49:10 +00:00
name = request.POST.get("name")
book_id = request.POST.get("book")
2021-01-13 18:24:24 +00:00
book = get_object_or_404(models.Edition, id=book_id)
2021-02-04 21:21:55 +00:00
tag_obj, _ = models.Tag.objects.get_or_create(
2021-01-13 18:24:24 +00:00
name=name,
)
2021-02-04 21:21:55 +00:00
models.UserTag.objects.get_or_create(
2021-01-13 18:24:24 +00:00
user=request.user,
book=book,
tag=tag_obj,
)
2021-03-08 16:49:10 +00:00
return redirect("/book/%s" % book_id)
2021-01-13 18:24:24 +00:00
2021-03-08 16:49:10 +00:00
@method_decorator(login_required, name="dispatch")
2021-01-13 18:24:24 +00:00
class RemoveTag(View):
2021-03-08 16:49:10 +00:00
""" remove a user's tag from a book """
2021-01-13 18:24:24 +00:00
def post(self, request):
2021-03-08 16:49:10 +00:00
""" untag a book """
name = request.POST.get("name")
2021-01-13 18:24:24 +00:00
tag_obj = get_object_or_404(models.Tag, name=name)
2021-03-08 16:49:10 +00:00
book_id = request.POST.get("book")
2021-01-13 18:24:24 +00:00
book = get_object_or_404(models.Edition, id=book_id)
user_tag = get_object_or_404(
2021-03-08 16:49:10 +00:00
models.UserTag, tag=tag_obj, book=book, user=request.user
)
2021-01-13 18:24:24 +00:00
user_tag.delete()
2021-03-08 16:49:10 +00:00
return redirect("/book/%s" % book_id)