首页 > 解决方案 > 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 上。

标签: djangopython-3.x

解决方案


您收到错误是因为您尝试使用 2 个参数(view_typecurr_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', '/'))

推荐阅读