Redirect / return to same (previous) page in Django?

前提是你 提交于 2019-11-28 16:58:18

问题


What are the options when you want to return the user to the same page in Django and what are the pros/cons of each?

Methods I know:

  • HTTP_REFERER
  • GET parameter containing the previous URL
  • Session data to store the previous URL

Are there any other?


回答1:


One of the way is using HTTP_REFERER header like as below:

from django.http import HttpResponseRedirect

def someview(request):
   ...
   return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

Not sure of cons of this!




回答2:


While the question and answer is old, I think it's lacking a few options. I have not find any cons with the methods, I would be happy to know if there are any?

  • request.path_info
  • request.get_full_path()
  • request.build_absolute_uri()

    from django.shortcuts import redirect
    
    redirect(request.path_info) # No query parameters
    
    redirect(request.build_absolute_uri()) # Keeps query parameters
    
    redirect(request.get_full_path()) # Keeps query parameters
    



回答3:


100% working Example

For Class Based View and Function:

from django.http import HttpResponseRedirect
    ...
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

or

from django.http import HttpResponseRedirect
    ...
    return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))

Example -

class TaskNotificationReadAllView(generic.View):

    def get(self, request, *args, **kwargs):
        TaskNotification.objects.filter(assigned_to=request.user).update(read=True)   
        print(request.META.get('HTTP_REFERER'))    
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))


来源:https://stackoverflow.com/questions/12758786/redirect-return-to-same-previous-page-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!