Django POST URL error

后端 未结 6 1627
栀梦
栀梦 2020-12-11 14:30

I am trying to make a REST Api in Django by outputting Json. I am having problems if i make a POST request using curl in terminal. The error i get is

相关标签:
6条回答
  • 2020-12-11 14:59

    FOR GET ==>http://127.0.0.1:8000/create?name=wpwqekhqw/

    For POST ==> http://127.0.0.1:8000/create/?name=wpwqekhqw/

    You should add '/' after create in POST ... request

    0 讨论(0)
  • 2020-12-11 14:59

    Another scenario can raise the exact error, not related to either csrf or APPEND_SLASH solution, below an example.

     def post(self, request, *args, **kwargs):
            data= request.data
            print(data['x'])
    

    If 'x' does not exist in the payload body, the data['x'] will raise an error, this error in my case gave a false message like the above one. Hopefully, this will help other developers.

    0 讨论(0)
  • 2020-12-11 15:16

    For URL consistency, Django has a setting called APPEND_SLASH, that always appends a slash to the end of the URL if it wasn't sent that way to begin with. This ensures that /my/awesome/url/ is always served from that URL instead of both /my/awesome/url and /my/awesome/url/.

    However, Django does this by automatically redirecting the version without the slash at the end to the one with the slash at the end. Redirects don't carry the state of the request with them, so when that happens your POST data is dropped.

    All you need to do is ensure that when you send your POST, you send it to the version with the slash at the end.

    0 讨论(0)
  • 2020-12-11 15:18

    Make change in action in Html. It's worked in my case.

    <form action="{% url 'add' %}" method="post">
        {% csrf_token %}
        ...
    </form>
    
    0 讨论(0)
  • 2020-12-11 15:20

    Simply remove trailing slash from your URLs

    urlpatterns = [
        path('', views.home, name= 'home'),
        path('contact/', views.contact, name= 'contact'),
        path('about/', views.about, name= 'about')
    ]
    

    Change to

    urlpatterns = [
        path('', views.home, name= 'home'),
        path('contact', views.contact, name= 'contact'),
        path('about', views.about, name= 'about')
    ]
    

    OR

    Add trailing slash to action in HTML Form

     <form method="POST" action="/contact/">
        {% csrf_token %}
    

    It worked for me

    0 讨论(0)
  • 2020-12-11 15:23

    First, make sure that you send the request to http://127.0.0.1/add/ not http://127.0.0.1/add.

    Secondly, you may also want to exempt the view from csrf processing by adding the @csrf_exempt decorator - since you aren't sending the appropriate token from cURL.

    0 讨论(0)
提交回复
热议问题