2

我知道我们不应该使用 stackoverflow 进行调试,但我在过去 10 小时内一直在尝试解决这个问题,我感到无望,我很抱歉。

#main project urls.py:
urlpatterns = [
    ...
    path('accounts/',include('employee.urls')),
    ...
]...

#employee.urls:
urlpatterns = [
    ...
    path('employees/', views.display_employees),
    path('edit/<str:employee_ssn>/', views.edit_employee),
    ...
]

#views.py - edit_employee being used only for testing by now
def display_employees(request):
    logged_user = request.user
    queryset = Employee.objects.filter(company=logged_user.company)
    context = {
        'employees': queryset
    }
    return render(request, 'employees.html', context)

def edit_employee(request, employee_ssn):
    context = {}
    emp = Employee.objects.filter(ssn=employee_ssn)
    
    context = {
        'employee_list': emp
    }
    return render(request, 'edit-employee.html', context)

#employees.html
<ul>
    {% for obj in employees %}
    <li>{{ obj.name }}</li>
    <li>{{ obj.ssn }}</li>
    <li>{{ obj.email }}</li>
    <li><a href="{% url '/accounts/edit/' obj.ssn %}">edit</a></li><br>
    {% endfor %}
</ul>

#edit-employee.html
<ul>
{% for obj in employee_list %}
    <li>{{ obj.name }}</li>
    <li>{{ obj.ssn }}</li>
    <li>{{ obj.email }}</li>
{% endfor %}
</ul>

当它被点击时,edit它说:

异常类型:NoReverseMatch 异常值:未找到“/accounts/edit/”的反向。'/accounts/edit/' 不是有效的视图函数或模式名称。

但是,如果在http://localhost:8000/accounts/edit/<employee_snn>/浏览器上键入url,则edit-employee.html正常呈现。它还说错误出现在我的第 0 行的基本模板中

4

1 回答 1

1

您不能在模板标签 [Django-doc]中使用“模式” 。您应该为视图命名,然后使用它来解析 url,因此:{% url … %}

urlpatterns = [
    # …
    path('employees/', views.display_employees),
    path('edit/<str:employee_ssn>/', views.edit_employee, name='edit-employee'),
    # …
]

and then you can use this as parameter in the {% url … %} tag:

<li><a href="{% url 'edit-employee' obj.ssn %}">edit</a></li><br>

The idea of using an {% url … %} tag is that you can easily change the path patterns. As long as the name remains the same, and the parameters, it will still be able to resolve the template path.

于 2020-09-29T18:48:55.610 回答