首页 > 解决方案 > Django:没有反向匹配。如何反转到上一个 URL?

问题描述

我有一个模型类Client,这个模型对象的 URL 是

<local_server>/object_id/

object_idmodel的id对象在哪里Client

现在,当我访问此 URL 时,页面上有一个按钮,Add Installment用于添加该特定Client. 当我单击此按钮时,它会将我带到以下 URL:

<local_server>/object_id/add_installment

现在,如果我添加新的分期付款,它工作正常。但是Add Installment页面有两个按钮,AddCancel。我希望如果我单击Cancel它应该返回以下 URL:

<local_server>/object_id/

为此,我有以下用于添加分期付款的模板,您可以在其中看到Cancel 按钮。

installment_form.html

{% extends "client_management_system/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content_section">
    <form method="post">
      {% csrf_token %}
      <fieldset class="form-group">
        <legend class="border-bottom mb-4"> Add New Installment</legend>
        {{ form|crispy }}
      </fieldset>
      <div class="form-group">
        <button class="btn btn-outline-success" type="submit">Add Installment</button>
        <a class="btn btn-outline-danger" type = "submit" href="{%  url 'client_details' object.id %}" >Cancel</a>
      </div>
    </form>
</div>

{% endblock %}

Cancel按钮中,client_details是 URL 的名称<local_server>/object_id。我已经object.id在该行中写了,但是当我单击时,Add Installment我收到以下错误:

NoReverseMatch at /1/Add-Installment
Reverse for 'client_details' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)\\/$']
Request Method: GET
Request URL:    http://127.0.0.1:8000/1/Add-Installment
Django Version: 3.2
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'client_details' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)\\/$']
Exception Location: /anaconda3/lib/python3.6/site-packages/django/urls/resolvers.py, line 694, in _reverse_with_prefix
Python Executable:  /anaconda3/bin/python3
Python Version: 3.6.10
Python Path:    
['/Users/razajaved/Documents/installment_plan',
 '/anaconda3/lib/python36.zip',
 '/anaconda3/lib/python3.6',
 '/anaconda3/lib/python3.6/lib-dynload',
 '/anaconda3/lib/python3.6/site-packages',
 '/anaconda3/lib/python3.6/site-packages/aeosa']
Server time:    Wed, 21 Apr 2021 20:49:32 +0000

有人可以帮我吗?

标签: pythondjangodjango-modelsdjango-viewsdjango-templates

解决方案


我找到了两种方法来做到这一点:

<local_server>/object_id/通过替换我的 html 文件中的以下行返回到上一个 URL :

<a class="btn btn-outline-danger" type = "submit" href="{%  url 'client_details' object.id %}" >Cancel</a>

有了这个:

<input type=button class="btn btn-outline-danger" value="Cancel" onClick="window.history.back();return false;">

或者这样:

<a class="btn btn-outline-danger" type = "submit" href="javascript:history.go(-1)">Cancel</a>

推荐阅读