【问题标题】:Is it ever necessary to instantiate new HttpRequest objects in Django?是否有必要在 Django 中实例化新的 HttpRequest 对象?
【发布时间】:2017-02-21 17:35:23
【问题描述】:

我有一个对用户进行身份验证的视图。如果用户通过了身份验证,程序应该以请求和用户作为参数调用另一个视图。

    def home(request):
        if request.method == "POST":
            username = request.POST.get('username')
            password = request.POST.get('password')
            user = authenticate(username=username, password=password)

            if user is not None:
                return index(request, user)
            else:
                 context = {'error_message': "That username and password don't exist in our system."}
                 return render(request, 'list/home.html', context)

所以,当 index 被调用时,请求与发送到主视图的请求是同一个实例,对吧?我担心的是,当它应该是 GET 请求时,它仍然是 POST 请求。

这是一种误解吗?我应该创建一个新的请求对象并将其发送到索引吗?

谢谢。

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    你应该使用redirect方法

    if user is not None:
        return redirect(reverse('index'))
    

    【讨论】:

      【解决方案2】:

      来自优秀的"What technical details should a programmer of a web application consider before making the site public?",

      如果 POST 成功,则在 POST 之后重定向,以防止再次提交刷新。

      所以您是对的,您需要重定向以确保未提交之前的表单。但除此之外,您不应将视图视为可直接链接的,而应认为视图是您从发出请求中得到的。因此,正如 afilardo 建议的那样,您应该重定向。

      return redirect('index')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-17
        相关资源
        最近更新 更多