django - django.urls.exceptions.NoReverseMatch:使用关键字参数反转“change_view”
问题描述
我收到错误
django.urls.exceptions.NoReverseMatch:使用关键字参数“{'view_type':'sla','curr_url':'/home/'}'反向'change_view'。尝试了 1 种模式:['change_view\/(?P[^/]+)\/$']
使用 django 2.1.7 和 python 3.6 版本
我试图将两个参数都添加为 urls.py 中的动态字段
主页.html
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true"><i class="fa fa-eye fa-fw"></i>View<span class="caret"></span></a>
<ul class="dropdown-menu">
<li {% if session.view == 'sla' %}class="disabled"{% endif %}><a href="{% url 'change_view' view_type='sla' curr_url=request.get_full_path %}"><i class="fa fa-bar-chart-o fa-fw"></i>SLA</a></li>
<li {% if session.view == 'priority' %}class="disabled"{% endif %}><a href="{% url 'change_view' view_type='priority' curr_url=request.get_full_path %}"><i class="fa fa-trophy fa-fw"></i>Priority</a></li>
</ul>
</li>
网址.py
urlpatterns = [
path('change_view/<str:view_type>/', views.change_view , name='change_view'),
]
视图.py
def change_view(request,view_type=None):
request.session['view'] = view_type
request_data = json.loads(request.body)
curr_url = request_data['curr_url']
return redirect(curr_url)
我希望函数 change_view 将 request.session['view'] 设置为用户选择的输入并保持在相同的 url 上。
解决方案
您收到错误是因为您尝试使用 2 个参数(view_type
和curr_url
)查找 url,但您只有 1 个属性(view_type
)。
考虑这个解决方案 - 您不会提供您的请求并使用请求标头curr_url
将用户发回。HTTP_REFERER
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true"><i class="fa fa-eye fa-fw"></i>View<span class="caret"></span></a>
<ul class="dropdown-menu">
<li {% if session.view == 'sla' %}class="disabled"{% endif %}><a href="{% url 'change_view' view_type='sla' %}"><i class="fa fa-bar-chart-o fa-fw"></i>SLA</a></li>
<li {% if session.view == 'priority' %}class="disabled"{% endif %}><a href="{% url 'change_view' view_type='priority' %}"><i class="fa fa-trophy fa-fw"></i>Priority</a></li>
</ul>
</li>
视图.py:
def change_view(request,view_type):
request.session['view'] = view_type
return redirect(request.META.get('HTTP_REFERER', '/'))
推荐阅读
- javascript - Vue.js 观察者重复输入给出空引用
- dialogflow-es - 如何在 dialogflow fullfilment 中为返回用户管理自定义?
- android - 使用类方法之类的函数
- javascript - 如何通过语义 UI 反应打开多个手风琴?
- javascript - 如何按顺序添加元素数组?
- magnolia - 将所有用户更改为大写的 Groovy 脚本
- prolog - CLP:“不是三个相同值”的有效模型
- html - 我的 .click 方法有时只有效,然后在其他时候出错
- recursion - 递归积 mips32
- java - 你如何序列化地图
或地图 与杰克逊一起进入 XML?