如何在 Django 中重定向到不同的 URL?

编程入门 行业动态 更新时间:2024-10-07 09:26:38
本文介绍了如何在 Django 中重定向到不同的 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个页面,一个是显示特定项目的详细信息,另一个是搜索项目.假设 urls.py 已为它们和我的应用程序在 views.py 中正确配置,我有:

I have two pages, one which is to display details for a specific item and another to search for items. Let's say that the urls.py is properly configured for both of them and within views.py for my app, I have:

def item(request, id): return render(request, 'item.html', data) def search(request): #use GET to get query parameters if len(query)==1: #here, I want to redirect my request to item, passing in the id return render(request, 'search.html', data)

我该怎么做才能正确重定向请求?我试过 return item(request, id) 并呈现正确的页面,但它不会更改地址栏中的 URL.我怎样才能让它真正重定向而不是仅仅呈现我的另一个页面?项目页面的 URL 模式是 /item/{id}.我已经查看了关于 SO 和文档的类似问题的答案,但仍然无法弄清楚.

What do I do to properly redirect the request? I've tried return item(request, id) and that renders the correct page, but it doesn't change the URL in the address bar. How can I make it actually redirect instead of just rendering my other page? The URL pattern for the item page is /item/{id}. I've looked at the answer to similar questions on SO and the documentation, but still couldn't figure it out.

我不到一周前才开始学习 Python,另一个答案不够清楚,无法帮助我.

I just started learning Python less than a week ago and the other answer isn't clear enough to help me out.

编辑 2:Nvm,不确定我之前做错了什么,但是当我再次尝试时它起作用了.

Edit 2: Nvm, not sure what I did wrong before, but it worked when I tried it again.

推荐答案

您可以使用 HttpResponseRedirect:

You can use HttpResponseRedirect:

from django.http import HttpResponseRedirect # ... return HttpResponseRedirect('/url/url1/')

url"在哪里和url1"等于重定向的路径.

Where "url" and "url1" equals the path to the redirect.

更多推荐

如何在 Django 中重定向到不同的 URL?

本文发布于:2023-11-02 07:01:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551688.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重定向   如何在   Django   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!