Home > Software design >  How to redirect to same page after form action in django
How to redirect to same page after form action in django

Time:09-30

I'm new to Django and I'm trying to create an app which will accept multiple images upload using forms and then redirect to the same upload page and display uploaded images just below the form.

My program works for uploading, but then I cannot exactly redirect it back to the same page which contains the upload form and images.

index.html(in templates folder)

    <form>
    action="{% url 'fileapp:uploads' %}"
    method="POST"
    enctype="multipart/form-data" >
    <input type="text" name="filename" placeholder="enter your file name" />
    <input type="file" multiple name="uploadfoles" />
    {% csrf_token %}
    <button type="submit">File Upload</button>
    </form>
    <h3>Previously uploaded files: <br></h3>    
    {% for d in data %}

    <p>{{d.f_name}} ---- <img width="50" src="{{d.myfiles.url}}" /></p>

    {% endfor %}

views.py

from . models import myuploadfile
 def index(request):
context = {
    "data":myuploadfile.objects.all(),
}
return render(request,"index.html",context)

def send_files(request):
if request.method == "POST" :
    name = request.POST.get("filename")
    myfile = request.FILES.getlist("uploadfoles")
    
    for f in myfile:
        myuploadfile(f_name=name,myfiles=f).save()
    
    return redirect("fileapp:index")

urls.py

from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
path('admin/', admin.site.urls),
path("",include("myfileapp.urls",namespace="fileapp"))
]

urlpatterns  = static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns  = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Whenever I press 'File Upload' button, the app should redirect back to the same page where we upload files, but I get this error:

NoReverseMatch at /upload Reverse for 'index' not found. 'index' is not a valid view function or pattern name.

CodePudding user response:

Apparently you dont have anything like fileapp:index in your urls.py. Nonetheless, you can redirect to the current page by using .

return redirect('.')
  • Related