django.urls.exceptions.NoReverseMatch:带有关键字参数的'change_view'的反向

时间:2019-05-16 08:39:07

标签: django python-3.x

我遇到错误

  

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中的动态字段

home.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>

urls.py

urlpatterns = [
    path('change_view/<str:view_type>/', views.change_view , name='change_view'),
]

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上。

1 个答案:

答案 0 :(得分:2)

由于尝试查找带有2个参数(view_typecurr_url)的url,但只有1个属性(view_type)的URL,所以出现错误。
考虑这种解决方案-您将不会向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>

views.py:

def change_view(request,view_type):
    request.session['view'] = view_type
    return redirect(request.META.get('HTTP_REFERER', '/'))