简体   繁体   中英

Django redirecting to a different view in another app

There are many similar questions to mine on Stack Overflow, but none which solve my problem.

I have a class-based view which accepts files, and once a valid file is found, I would like the website to redirect the user to a template inside a different app, passing in some parameters.

I've seen others put an extra path in 'urlpatterns' and get the view from there. But doing this only makes a GET signal on my command prompt, but not actually changing the web url.

views.py

from django.shortcuts import render, redirect   # used to render templates
from django.http import JsonResponse
from django.views import View

from .forms import UploadForm
from .models import FileUpload

class UploadView(View):
    def get(self, request):
        files_list = FileUpload.objects.all()
        return render(self.request, 'upload/upload.html', {'csv_files': files_list})

def post(self, request):
    form = UploadForm(self.request.POST, self.request.FILES)
    if form.is_valid():
        csv_file = form.save()
        data = {'is_valid': True,
                'name': csv_file.file.name,
                'url': csv_file.file.url,
                'date': csv_file.uploaded_at}
        # REDIRECT USER TO VIEW PASSING 'data' IN CONTEXT
        return redirect('graph:chart', file_url=csv_file.file.url)
    else:
        data = {'is_valid': False}
    return JsonResponse(data)

urls.py

from django.urls import path
from . import views

app_name = "upload"

urlpatterns = [
    path('', views.UploadView.as_view(), name='drag_and_drop'),
]

urls.py (of other app)

from django.urls import path
from . import views

app_name = "graph"

urlpatterns = [
    path('', views.page, name='chart'),
]

You can specify an app name and use exactly the redirect shortcut as you started: https://docs.djangoproject.com/en/2.1/topics/http/urls/#naming-url-patterns

in the other app urls.py define app_name = 'other_app' , and then use redirect(other_app:url_name', parameter1=p1, parameter2 = p2)

you can name easily your parameters either using path (Django >=2.0) or url ( re_path for Django >=2.0), for instance:


from django.urls import path

from . import views

urlpatterns = [
    path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
    re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM