How do you handle POST requests in Django

How do you handle POST requests in Django on PythonAnywhere? The help pages only seem to cover GET requests (which work fine). Got various errors, currently 'Forbidden (Referer checking failed - no Referer.)'. Does urls.py work the same way for POSTs?

The error you mentioned: Forbidden (Referer checking failed - no Referer) is NOT related to urls.py. It is Django’s CSRF protection blocking the request.

Django requires a CSRF token for POST requests coming from forms or API calls.

Btw, yes, urls.py works the same for POST as it does for GET. Django does not differentiate at the URL routing level. The difference is handled inside the view.

A simple example:

urls.py

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("submit/", views.submit_form, name="submit_form"),
]

views.py

# views.py
from django.http import JsonResponse

def submit_form(request):
    if request.method == "POST":
        value = request.POST.get("value")
        return JsonResponse({"received": value})
    else:
        return JsonResponse({"error": "POST required"}, status=405)

If you are submitting from a template form, you must include the CSRF token:

<form method="post">
    {% csrf_token %}
    <input type="text" name="value">
    <button type="submit">Submit</button>
</form>

Another common cause on PythonAnywhere is a domain mismatch between the site and the request origin. In that case you may need to add your domain to CSRF_TRUSTED_ORIGINS in settings.py.

CSRF_TRUSTED_ORIGINS = ["https://yourusername.pythonanywhere.com"]

urls.py in Django works perfectly for any type of header requests. The main part of handling what type of request it comes from is mostly from the Django view that is in views.py. However, you do have this Forbidden (Referer checking Failed...) error, which is Django's security system (the CSRF system) popping up. If the view that is handling post requests is handling a form, then, inside the <form></form> tag, you need to place {%csrf_token%} at the very beginning and set action in the form tag empty or put in the URL of the view that handles the logic. If this view is for, let's say, an API or endpoint of some sort (will the POST management of true APIs is somewhat different), then one of the ways (best for development) is to set the csrf_exempt decorator at the top of the view. However, DO NOT do this with forms.

Thankyou. Working on something else atm, but I'll look into all of those.

Вернуться на верх