Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django在HttpResponseRedirect期间引发404错误,但在刷新后显示当前页面_Python_Django_Django Views_Django Urls - Fatal编程技术网

Python Django在HttpResponseRedirect期间引发404错误,但在刷新后显示当前页面

Python Django在HttpResponseRedirect期间引发404错误,但在刷新后显示当前页面,python,django,django-views,django-urls,Python,Django,Django Views,Django Urls,我有一个名为“以后阅读”的页面,其中存储了用户以后阅读的帖子。稍后我会在导航栏上看到。现在,当用户没有read later帖子并单击read later时,用户将重定向回原始页面。我有一个基于函数的def供以后阅读 views.py: def show_readlater(request, *args): global redirect global redirect_lock global return_address if not(redirect_lock)

我有一个名为“以后阅读”的页面,其中存储了用户以后阅读的帖子。稍后我会在导航栏上看到。现在,当用户没有read later帖子并单击read later时,用户将重定向回原始页面。我有一个基于函数的def供以后阅读

views.py:

def show_readlater(request, *args):
    global redirect
    global redirect_lock
    global return_address
    if not(redirect_lock):
        redirect = None
    else:
        redirect_lock = False
    if not(request.user.is_authenticated()):
        raise PermissionDenied
    else:
        user_instance = User.objects.get(username = request.user.username)
        userprofile_instance = UserProfile.objects.get(user = user_instance)
        readlater_objects = ReadLaterList.objects.all()
        readlater_list = []
        count = 0
        for x in readlater_objects:
            if x.username == request.user.username:
                readlater_post = Post.objects.get(slug = x.slug)
                readlater_list.append(readlater_post)
                count = count + 1
        if count == 0 :
            redirect = "no_readlater"
            redirect_lock = True
            return HttpResponseRedirect(return_address)   # The user is redirect back to the original page
        post_title = "Read Later" 
        template = "posts/show_posts.html"
        dictionary = {
            "total_posts"    : readlater_list,
            "title"          : post_title,
            "count"         : count,
            "redirect"      : redirect,

        }
        return render(request, template, dictionary)
这里,
redirect
将在原始页面中显示一条消息,说明没有“以后阅读”的帖子

问题是,当重定向发生时,Django说找不到页面,但刷新后页面被加载


发生了什么事?

确保全局变量“return\u address”中指定的url正确,并在应用程序/url.py中指定。

首先更改此设置

    global redirect
    global redirect_lock
    global return_address

对于所有全局变量


使用
redirect
而不是
HttpResponseRedirect

在Django中不能使用这样的全局变量,它会导致竞争条件。那么我如何返回原始页面并发送消息?您使用会话。哦,好的。。我试试看。那应该有帮助@KlausD:通过会话,任务变得更简单、更清晰。谢谢我有一个类似的搜索功能,它可以正常重定向。404错误是因为我阻止了某些重定向。我没有注意到。但是使用会话使它变得非常简单。谢谢顺便问一下,在加载网站中的任何页面之前,是否有初始化会话的init方法?
request.session['redirect']= redirect