Home > Net >  How to get user with POST Ajax call in django?
How to get user with POST Ajax call in django?

Time:01-05

I'm trying to realize comments for products on site with AJAX, but faced the problem that I can not receive an author of comment in this case of code:

new_comment.author = request.user

I got this error in this case: "Exception Value:

Object of type User is not JSON serializable"

But without user I got parameters from back-end and have result 200, like this

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

So the question how to be "author = request.user" can be serialized? Or it is can be realised only with Django Rest Framework? (I don't have experience in DRF, but know some things in theory)

Can somebody advice please?

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)

Thank you all for recommendations! Finnaly I did with Django Rest Framework and there is the last version of code, hope it would help somebody who faced the same issue. Don't forget to create serializer you need in serializers.py and import modules that DRF needs:

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)

CodePudding user response:

In your case, you are trying to convert the User model object into json. But JsonResponse use the json.dumps method for the conversion. And it can't convert the model, class, and complex objects into json. Though JsonResponse has some special functionality like it can convert the datetime and uuid fields.

For your case, I think creating an author dict manually will be better.

  • Just change into comment_info dict and it will look like this.

          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,
          }
    

Now you can use JsonResponse({"comment_info": comment_info}, status=200) for json response.

  •  Tags:  
  • Related