Home > Blockchain >  Django redirect from form upload
Django redirect from form upload

Time:12-21

From the page

This page isn’t working. If the problem continues, contact the site owner.
HTTP ERROR 405

From the terminal

Method Not Allowed (POST): /
Method Not Allowed: /
[20/Dec/2021 22:00:27] "POST / HTTP/1.1" 405 0

How to redirect to the same page after page upload click.

form.html->included in sidebar.html-> included in home.html

<form method = "POST" action='.' enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>

views.py

from django.shortcuts import render
from .forms import UserProfileForm

def index(request):
    print(request.POST)
    return render(request,'home.html')

urls.py

from django.conf import settings
from django.urls import path
from django.views.generic.base import TemplateView # new

urlpatterns = [
    path('', TemplateView.as_view(template_name='home.html'), name='home'), 
]

CodePudding user response:

In your urls.py

Change to:

path(' ', index, name = 'home'),

And you also have to import your view in urls.py

CodePudding user response:

Since you are redirecting to the same page, I assume you are also making a get request when you are serving the form on the webpage. But when the page is served as a response to a GET request, it is not supposed to contain an empty dictionary in the POST attribute. Thus, it provides an error. According to me

def index(request):
    if request.method == "POST" :
        print(request.POST)
    return render(request,'home.html')

Should solve the issue

Acc, to the Django documentation

It’s possible that a request can come in via POST with an empty POST dictionary – if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn’t use if request.POST to check for use of the POST method; instead, use if request.method == "POST"

For further reference - https://docs.djangoproject.com/en/3.2/ref/request-response/

  • Related