@MalikDeveloper2077

Django Rest Framework, TypeError: __init__() takes 1 positional argument but 2 were given. Почему происходит?

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)


Получаю такую ошибку

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


Во фронт енде посылаю просто ajax запрос. Из-за чего ошибка?
  • Вопрос задан
  • 113 просмотров
Решения вопроса 1
@Realmixer
Full stack Python (Django) web-developer
Ошибка в urls.py, неправильно прописан класс отображения — не хватает вызова метода as_view. Надо так:
urlpatterns = [
    path('quiz/bookmark/create-remove/<slug:slug>/', views.CreateRemoveBookmarkAPI.as_view(),
        name="bookmark-create-remove-api"),
]
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы