Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Test Client client.post() sends GET request?

Tags:

http

django

I am new to Python and Django. I did a experiment on enforcing request method (e.g. for certain url you can only use GET). Here is my code.

tests.py

from django.test import TestCase, Client
client = Client()

class MyTests(TestCase):
    def test_request_method:
        """ Sending wrong request methods should result in 405 error """
        self.assertEqual(client.post('/mytest', follow = True).status_code, 405)

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name = 'index'),
    url(r'^mytest/', views.mytest, name = 'mytest'),
]

views.py

from django.http import HttpResponse

def mytest(request):
    if request.method == 'GET':
        return HttpResponse("Not implemented", status = 500)
    else:
        return HttpResponse("Only GET method allowed", status = 405)

But the test always returns status 500.

I saw here that this may be related to using follow=True in the client.post() call. However if I use follow=False I will get status 301 instead.

Any ideas? Thank you!

like image 569
yhf8377 Avatar asked Sep 11 '25 19:09

yhf8377


1 Answers

Does it perhaps redirect /mytest to /mytest/? The documentation suggests that by default, a trailing slash is added by doing a redirect if no URL pattern matches without the slash, and to quote:

Note that the redirect may cause any data submitted in a POST request to be lost.

A request caused by commonly used redirect status codes is always a GET request. You could either make the request to /mytest/ or remove the trailing slash from your URL pattern.

like image 95
Matti Virkkunen Avatar answered Sep 13 '25 10:09

Matti Virkkunen