def view_article(request, pk): ''' View one specific article. ''' queryset=get_object_or_404(Article.objects \ .prefetch_related('authors', 'commentaries', 'key_figures'), id=pk) serializer = ArticleSerializerNested(instance=queryset) return Response(serializer.data)
def update_article(request, pk): queryset = get_object_or_404(Article, id=pk) logging.warning(request.data) if request.method in ('PUT', 'PATCH'): user = request.user if ( not user.is_staff and not hasattr(request.user, 'author') ): #or (hasattr(request.user, 'author') and request.user.author not in queryset.authors.all()): # Only admins and authors can update articles. return Response("Forbidden", status=status.HTTP_403_FORBIDDEN) if request.method == "PATCH": is_partial = True else: is_partial = False serializer = ArticleSerializerNested(queryset, data=request.data, partial=is_partial) if serializer.is_valid(): serializer.save() response_data = serializer.data result_status = status.HTTP_200_OK else: response_data = serializer.errors result_status = status.HTTP_400_BAD_REQUEST return Response(response_data, status=result_status) else: serializer = ArticleSerializerNested(instance=queryset) return Response(serializer.data)
def create_article(request): if request.method == 'POST': user = request.user if not user.is_staff and not hasattr(request.user, 'author'): # Only admins and authors can add articles. # If the non-admin user has not created an author profile, they must do so # before curating articles. return Response("Forbidden", status=status.HTTP_403_FORBIDDEN) serializer = ArticleSerializerNested(data=request.data) if serializer.is_valid(): article = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: serializer = ArticleSerializerNested() return Response(serializer.data, status=status.HTTP_200_OK)