Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

python - How to make a Django-Rest-Framework API that takes POST data?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...