2

Models.py:

  class Bookmark(models.Model):
    """Bookmar for a quiz"""
    quiz = models.ForeignKey(
        Quiz,
        on_delete=models.PROTECT,
        verbose_name='Викторина',
        related_name='bookmarks'
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        verbose_name='Пользователь',
        related_name='bookmarks'
    )
    date = models.DateTimeField(auto_now_add=True, verbose_name='Дата добавления')

    def __str__(self):
        return f'{self.user} - {self.quiz}'

Urls.py:

urlpatterns = [
    path('quiz/bookmark/create-remove/<slug:slug>/', views.CreateRemoveBookmarkAPI,
        name="bookmark-create-remove-api"),
]

Views.py:

class CreateRemoveBookmarkAPI(APIView):
    """API for create or remove quiz bookmark.
    Get a quiz slug, and create or remove bookmark at it
    """
    permission_classes = (IsAuthenticated,)

    def post(self, request, slug):
        quiz = get_object_or_404(Quiz, slug=slug)
        bookmark = Bookmark.objects.filter(quiz=quiz, user=request.user)
        data = {}

        if bookmark.exists():
            bookmark.delete()
            data['bookmarked'] = False
        else:
            Bookmark.objects.create(quiz=quiz, user=request.user)
            data['bookmarked'] = True

        data['bookmarks'] = quiz.get_bookmarks_count()

        return Response(data, status=status.HTTP_200_OK)

I got it:

Internal Server Error: /api/quiz/bookmark/create-remove/dd-69/
Traceback (most recent call last):
  File "C:\Users\user\Desktop\quizapp\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\user\Desktop\quizapp\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\user\Desktop\quizapp\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given
[05/Mar/2020 12:04:33] "POST /api/quiz/bookmark/create-remove/dd-69/ HTTP/1.1" 500 21733

In front-end, I just send ajax request. The data attribute is empty because it doesn't matter. I don't know why it doesn't work. Please help me.

1 Answer 1

9

You didn't call as_view() function in your url

urlpatterns = [
    path('quiz/bookmark/create-remove/<slug:slug>/', views.CreateRemoveBookmarkAPI.as_view(),
        name="bookmark-create-remove-api"),
]
1
  • Simple thing but miss often and think about the complex things. Thank you for the solution
    – Bip Lob
    Oct 11, 2022 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.