Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm building a Django application with Django-Rest-Framework APIs. I have built an API endpoint as follows. I want to be able to POST data from my browser. I want to retrieve an object model from my Database that has the matching primary as given in the URL. And I want to operate on that retrieved object based on the data posted by the browser. If I could just grab the posted data from with my ViewSet, I would be done. But I don't know how to get to execute that viewset's update() function when I do a POST.

From my urls.py file:

router.register(r'replyComment', views.ReplyComment, base_name="replyComment")

From my views.py file:

class ReplyComment(viewsets.ViewSet):
    def update(self,request,pk=None):
        try: 
            origComment = Comment.objects.get(pk=pk)
            # Do something here that modifies the state of origComment and saves it.
            return Response(
                json.dumps(True), 
                status=status.HTTP_200_OK,
            )
        except Exception as exception:
            logger.error(exception)
            return Response(status=status.HTTP_400_BAD_REQUEST)

I'm using the Advanced Rest Client (ARC) tool in my Chrome browser. When I point the ARC tool to http://127.0.0.1:3001/api/replyComment/2/ using the POST method, I get the error:

{
    detail: "CSRF Failed: CSRF token missing or incorrect". 
}

See the screenshot here. It seems like I'm doing something wrong here with my POST. Can someone please advise how to do this properly? How can I get around my CSRF issue? I'm a newbie to Django Rest Frameworks. So if you can provide clear details, it would be most appreciated. Please let me know what changes I need to make to ensure my POST works as I intend it to? I need a bit more help than simply referring me to the manual. (I tried that but still couldn't make it work)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

CSRF Tokens are required in Django to protect against CSRF(Cross Site Request Forgery). For methods that writes something (POST, PUT, DELETE etc), you need to include a CSRF token with your request so that Django knows the request came from your own site.

You can read more about in Django-rest-framework documentation. And as it says in the doc, you can find how to include the CSRF token in the HTTP Header in Django documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...