python - django:无法重定向到 django 中的另一个视图
问题描述
我试图点击一个按钮http://127.0.0.1:8000/main/electronics/switch/
来调用getCommodityCommentDetail
做某事,然后重定向到另一个页面commodityInfoPage
。
令我困惑的是,该页面始终在初始页面中显示相同的内容,尽管 url 已更改为http://127.0.0.1:8000/main/comments/1/
.
经过测试,发现commodityInfoPage
没有调用views.py中的。我已经搜索了很长时间的解决方案,但都失败了。那么我该如何解决呢?
网址.py:
app_name = 'main'
urlpatterns = [
# eg:127.0.0.1:8000/main/
path('', views.index, name = 'index'),
path('getCommodityInfo/', views.getCommodityInfo, name = 'getCommodityInfo'),
path('getCommodityCommentDetail/', views.getCommodityCommentDetail, name="getCommodityCommentDetail"),
path('<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage'),
path('comments/<str:commodityId>/', views.commodityCommentPage,name = 'commodityCommentPage'),
]
视图.py:
def getCommodityCommentDetail(request):
if request.method=="POST":
commodityId = request.POST.get("commodityId")
# scrapy module is waiting implementation
#
return HttpResponseRedirect(reverse('main:commodityInfoPage',args=(commodityId)))
def commodityCommentPage(request, commodityId):
print("enter commodityCommentPage")
commentList = JDCommentDetail.objects.all()
context = {'commentList':commentList}
return render(request,'main/commodityCommentPage.html',context)
模板:
<form action="{% url 'main:getCommodityCommentDetail'%}" method="POST">
{% csrf_token %}
<input class="hidden" value="{{commodity.id}}" name="commodityId">
<button type="submit" class="btn btn-default" >review</button>
</form>
解决方案
问题是comments/1/
与commodityInfoPage
URL 模式匹配。
path('<str:category>/<str:searchKey>/',views.commodityInfoPage, name='commodityInfoPage'),
您可以通过更改 URL 模式以使其不会发生冲突,或将commodityCommentPage
URL 模式移到其上方来解决此问题commodityInfoPage
。
path('comments/<str:commodityId>/', views.commodityCommentPage, name='commodityCommentPage'),
path('<str:category>/<str:searchKey>/', views.commodityInfoPage, name='commodityInfoPage'),
请注意,如果您对模式重新排序,您将无法查看commodityInfoPage
类别是否为“评论”。
推荐阅读
- javascript - 如何在 jQuery 中转义哈希 (#) 字符
- php - 动态 URLs PHP-HTML
- git - 无法创建分支内容并将其推送到 GitHub 存储库
- java - 覆盖/禁用@Startup 类
- android - 如何更新 Flatlist 中的项目值
- html - 图像未损坏但未显示
- elasticsearch - 文档创建时的 ElasticSearch 格式字段
- php - 请问如何编辑此代码以显示最多 200,000 条记录的表的页面行选择器
- javascript - 一个 div 变大而另一个变小
- node.js - 无法使用 EB 单实例 NodeJS NGINX 配置将 HTTP 重定向到 HTTPS