NDOJ/judge/views/bookmark.py

87 lines
2.5 KiB
Python
Raw Normal View History

2022-11-17 19:17:45 +00:00
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.db.models import F
from django.http import (
Http404,
HttpResponse,
HttpResponseBadRequest,
HttpResponseForbidden,
)
from django.utils.translation import gettext as _
from judge.models.bookmark import BookMark, MakeBookMark
from django.views.generic.base import TemplateResponseMixin
from django.views.generic.detail import SingleObjectMixin
from judge.dblock import LockModel
from django.views.generic import View, ListView
__all__ = [
"dobookmark_page",
"undobookmark_page",
"BookMarkDetailView",
]
@login_required
def bookmark_page(request, delta):
if request.method != "POST":
return HttpResponseForbidden()
if "id" not in request.POST:
return HttpResponseBadRequest()
try:
bookmark_id = int(request.POST["id"])
bookmark_page = BookMark.objects.filter(id=bookmark_id)
except ValueError:
return HttpResponseBadRequest()
else:
if not bookmark_page.exists():
raise Http404()
if delta == 0:
2022-11-17 22:11:47 +00:00
bookmarklist = MakeBookMark.objects.filter(
bookmark=bookmark_page.first(), user=request.profile
)
2022-11-17 19:17:45 +00:00
if not bookmarklist.exists():
newbookmark = MakeBookMark(
bookmark=bookmark_page.first(),
user=request.profile,
)
newbookmark.save()
else:
2022-11-17 22:11:47 +00:00
bookmarklist = MakeBookMark.objects.filter(
bookmark=bookmark_page.first(), user=request.profile
)
2022-11-17 19:17:45 +00:00
if bookmarklist.exists():
bookmarklist.delete()
return HttpResponse("success", content_type="text/plain")
def dobookmark_page(request):
return bookmark_page(request, 0)
def undobookmark_page(request):
return bookmark_page(request, 1)
class BookMarkDetailView(TemplateResponseMixin, SingleObjectMixin, View):
def get_context_data(self, **kwargs):
context = super(BookMarkDetailView, self).get_context_data(**kwargs)
2022-11-17 21:45:27 +00:00
queryset = BookMark.objects.get_or_create(page=self.get_comment_page())
context["bookmark"] = queryset[0]
2022-11-17 19:17:45 +00:00
return context
2022-11-17 21:45:27 +00:00
2022-11-19 23:40:58 +00:00
class BookMarkListView:
2022-11-17 21:21:32 +00:00
def add_bookmark_context_data(self, context, obj_list="object_list"):
for item in context[obj_list]:
2022-11-17 19:17:45 +00:00
bookmark, _ = BookMark.objects.get_or_create(
page=self.get_comment_page(item)
)
setattr(item, "bookmark", bookmark)
2022-11-17 22:11:47 +00:00
return context