Skip to main content
 首页 » 编程设计

python之render_to_response 或 redirect 更改了 Django 1.8 中的模板元素

2025年05月04日40shanyou

我正在尝试检查用户输入的电子邮件 ID 是否存在于数据库表中,如果存在 - 我想路由到“prof.html”模板,否则只在 login.html 模板中显示一条消息。

两种情况都正常。

但是,问题是当我使用 redirect() 或 render_to_response() - div、input 等目标模板元素正在自动更改(在本例中为 prof.html)?

我们也可以将上下文信息发送到目标模板吗? (在这种情况下,响应数据或数据库中的任何对象并通过 View 重定向到 prof.html 模板)

下面是我的代码:

Views.py

def verifyme(request): 
    if request.method == "POST": 
        emailid4loginV = request.POST['emailid4login_Aj'] 
    else: 
        emailid4loginV = ''  
        response_data = '' 
        return HttpResponse(response_data, content_type="text/plain") 
    response_data = '' 
    if Employee.objects.filter(email = emailid4loginV).exists(): 
        response_data='Thanks for waiting - login successful' 
        #return render_to_response('app/prof.html', { 'response_data':response_data},  
        #                           context_instance = RequestContext( request ) ) 
        return redirect('/myprofile') 
    else: 
        response_data='Ouch! you are not a registered user!' 
    return HttpResponse(response_data, content_type="text/plain") 

urls.py

url(r'^myprofile$', 'app.views.profile', name='profile'), 

仅供引用,'profile' View 确实从表中返回一些对象并呈现在模板 app/prof.html 中。

我观察到目标模板在同一个 login.html 模板中呈现(如何?:在浏览器 url 中,我没有看到 myprofile - 但看到用于登录的那个)但是当我通过输入网站手动请求 myprofile 时url (localhost:xxxxx/myprofile),它完美地工作:(

在 login.html 中提交请求之前的 URL:

在 login.html 中提交请求后的 URL - myprofile 在同一页面中呈现:

当我手动输入 url 时,模板工作得很好..

你能告诉我可能是什么问题吗?

编辑: 用一个小技巧解决了这个问题,贴在下面

https://stackoverflow.com/questions/31091938/why-is-httpresponseredirectreverse-doesnt-redirect-to-new-page

请您参考如下方法:

1) 实际上有很多方法可以将数据传递到下一个 View ......通常在这种情况下你有更好的方法 - 使用 session (cookie | localstorage | sessionstorage),就像剪贴板一样......将 session 数据保存在一个 View ,稍后在另一个 View 中获取它。例如:

第一 View :

self.request.session['response_data'] = 'some text' 
self.request.session.set_expiry(0)  # user’s session cookie will expire when the user’s Web browser is closed. 

其他观点:

response_data = self.request.session.get('response_data', '') 

但是,如果您计划只在模板中使用此数据,Django 有某种更高级的接口(interface),在您的情况下语义上正确使用它 - 消息框架 https://docs.djangoproject.com/en/1.8/ref/contrib/messages/

2) 如果您想重定向到另一个 View ,最好使用 url 命名空间和 reverse https://docs.djangoproject.com/en/1.8/ref/urlresolvers/#reverse

return HttpResponseRedirect(reverse(app.views.profile))  # here I've passed callable object because you have not show your app url namespace, but generally use namespaces 

https://docs.djangoproject.com/en/1.8/topics/http/urls/#url-namespaces