#django #django-models #django-rest-framework #django-views
#django #django-модели #django-rest-framework #django-views
Вопрос:
Я получаю AssertionError в представлении articledetails. Я получаю следующую ошибку
AssertionError: Expected view ArticleDetailView to be called with a URL keyword argument named "user". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.
Я хочу использовать RetrieveAPIView для конечных точек, доступных только для чтения, для представления одного экземпляра модели.
Где я ошибся? И каков правильный способ исправить это? ниже мой view.py файл
class ArticleDetailView(RetrieveAPIView):
serializer_class = ArticleDetailSerial
permission_classes = [permissions.AllowAny]
lookup_field = 'user'
queryset = ArticleDetail.objects.all()
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
instance = self.get_object() # here the object is retrieved
serializer = self.get_serializer(instance)
return Response(serializer.data)
def get_object(self):
"""
Returns the object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if objects are referenced using multiple
keyword arguments in the url conf.
"""
queryset = self.filter_queryset(self.get_queryset())
# Perform the lookup filtering.
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
assert lookup_url_kwarg in self.kwargs, (
'Expected view %s to be called with a URL keyword argument '
'named "%s". Fix your URL conf, or set the `.lookup_field` '
'attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
)
filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs) # <-- can see that filtering is performed on the base of 'lookup_field'
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj # will return the single retrieved object
и это мой url.py
path('details/', ArticleDetailView.as_view()),
path('details/<int:pk>', ArticleDetailView.as_view()),
Комментарии:
1. удалите
lookup_field
атрибут из класса представления2. более того, что вы получили от переопределения этих трех методов? При быстром просмотре я не смог найти никаких различий с оригиналом.