没有反向匹配错误,但函数存在?

时间:2018-05-14 15:49:46

标签: django django-templates django-views

我正在尝试为关键广告资源系统实施renew功能。但是当我渲染该页面时,它显示了一个Reversematcherror,即使我映射了正确的URL并使用了正确的函数名称。

这是我的模板:( URL标签位于超长行一直到右边)

{% block content %}
    <h1>All Borrowed Keys</h1>

    {% if keyinstance_list %}
    <ul>

      {% for keyinst in keyinstance_list %} 
      <li class="{% if keyinst.is_overdue %}text-danger{% endif %}">
        <a href="{% url 'roomkey-detail' keyinst.roomkey.pk %}">{{keyinst.roomkey}}</a> 
        ({{ keyinst.due_back }}) 
        {% if user.is_staff %}
           - {{ keyinst.borrower }}
        {% endif %} 
        {% if perms.catalog.can_mark_returned %}
           - <a href="{% url 'renew_key_user' keyinst.id %}">Renew</a>  
        {% endif %}
      </li>
      {% endfor %}
    </ul>

    {% else %}
      <p>There are no keys borrowed.</p>
    {% endif %}  

{% endblock %}

我的urls.py:

path('key/<uuid:pk>/renew/', views.renew_key_user, name='renew-key-user'),
path('key/<int:pk>/detail', views.KeyDetailView.as_view(), name='roomkey-detail'),

Views.py:

@permission_required('catalog.can_mark_returned')
def renew_key_user(request, pk):
    """
    View function for renewing a specific keyInstance by admin
    """
    key_inst=get_object_or_404(KeyInstance, pk = pk)

    # If this is a POST request then process the Form data
    if request.method == 'POST':

        # Create a form instance and populate it with data from the request (binding):
        form = RenewKeyForm(request.POST)

        # Check if the form is valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
            key_inst.due_back = form.cleaned_data['renewal_date']
            key_inst.save()

            # redirect to a new URL:
            return HttpResponseRedirect(reverse('all-borrowed-keys') )

    # If this is a GET (or any other method) create the default form.
    else:
        proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
        form = RenewKeyForm(initial={'renewal_date': proposed_renewal_date,})

    return render(request, 'catalog/roomkey_renew_user.html', {'form': form, 'keyinst':key_inst})



class KeyDetailView(generic.DetailView):
    model = RoomKey

错误是

  

反转&views; .renew_key_user&#39;未找到。 &#39; views.renew_key_user&#39;   不是有效的视图函数或模式名称。

3 个答案:

答案 0 :(得分:0)

您的模板要求'roomkey-detail',但您提供的网址摘要仅显示名为'renew-key-user'的网址。除非您没有向我们展示更多网址定义,否则代码会按预期失败,因为它无法找到具有您要求的名称的网址。

答案 1 :(得分:0)

您的网址包含-连字符而不是_下划线

将此renew_key_user更改为模板中的renew-key-user

 <a href="{% url 'renew-key-user' keyinst.id %}">Renew</a>

答案 2 :(得分:0)

在模板中更新此行。

<a href="{% url 'renew-key-user' keyinst.id %}">Renew</a>

url中的名称是renew-key-user

path('key/<uuid:pk>/renew/', views.renew_key_user, name='renew-key-user'),