【问题标题】:How to get user with POST Ajax call in django?如何在 django 中使用 POST Ajax 调用获取用户?
【发布时间】:2021-12-31 07:39:38
【问题描述】:

我正在尝试使用 AJAX 为现场产品实现 cmets,但遇到的问题是在这种代码案例中我无法收到作者的评论:

new_comment.author = request.user

在这种情况下我得到了这个错误:“异常值:

User 类型的对象不是 JSON 可序列化的"

但是在没有用户的情况下,我从后端获取了参数,结果为 200,就像这样

author  ""
content "dasda"
created_at  "2021-12-31T07:34:12.766Z"
product 4

那么“author = request.user”这个问题怎么可以序列化呢?还是只能用 Django Rest Framework 才能实现? (我没有DRF的经验,但理论上知道一些事情)

有人可以建议吗?

def ajax_receiver(request):
    product = Product.objects.get(id=4)
    is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
    if request.method == 'POST' and is_ajax and request.user.is_authenticated:
        form = UserCommentForm(data=request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            #new_comment.author = request.user
            new_comment.product = product
            new_comment.save()
            comment_info = {
            "author": new_comment.author,
            "content": new_comment.content,
            "created_at": new_comment.created_at,
            "product": product.id,
            }
            return JsonResponse({"comment_info": comment_info}, status=200)
    else:
        return JsonResponse({"success": False}, status=400)

谢谢大家的推荐! Finnaly 我用 Django Rest Framework 做了最后一个版本的代码,希望它能帮助遇到同样问题的人。不要忘记在 serializers.py 中创建您需要的序列化程序并导入 DRF 需要的模块:

from .serializers import CommentSerializer
from rest_framework.response import Response
from rest_framework.decorators import api_view

@api_view(['POST'])
def ajax_receiver(request):
    product = Product.objects.get(id=4)
    is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
    if request.method == 'POST' and is_ajax and request.user.is_authenticated:
        form = UserCommentForm(data=request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.author = request.user
            new_comment.product = product
            new_comment.save()
            serializer = CommentSerializer(new_comment, many=False)
            return Response(serializer.data, template_name='ajax_test.html')
    else:
        return JsonResponse({"success": False}, status=400)

【问题讨论】:

    标签: django ajax serialization django-views django-forms


    【解决方案1】:

    在您的情况下,您正在尝试将 User 模型对象转换为 json。但是 JsonResponse 使用 json.dumps 方法进行转换。并且它无法将模型、类和复杂对象转换为json。虽然 JsonResponse 有一些特殊的功能,比如它可以转换日期时间和 uuid 字段。

    对于您的情况,我认为手动创建作者字典会更好。

    • 只要改成 comment_info dict,它就会变成这样。

            comment_info = {
               "author": {
                  "name": new_comment.author.name,
                  "id": new_comment.author.id
                  # -------- so on
               },
               "content": new_comment.content,
               "created_at": new_comment.created_at,
               "product": product.id,
            }
      

    现在您可以使用JsonResponse({"comment_info": comment_info}, status=200) 进行 json 响应。

    【讨论】:

    • +1 用于 DRF。它的功能很容易让人不知所措,但如果您能对序列化程序的工作原理有一个基本的了解,那就太棒了。
    • 谢谢!我会试试。已经有了 id 的这个想法,就像我对 product 所做的那样,但无法弄清楚如何实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多