首页 > 解决方案 > 模板渲染时出错 未找到“组编辑”的反向。'group-edit' 不是有效的视图函数或模式名称

问题描述

加载“group_list.html”时出现错误:找不到“group-edit”的反向。'group-edit' 不是有效的视图函数或模式名称。

如果我禁止此 href 引用,它可以工作,但我需要它才能编辑组实例

这是我对 group_edit 的views.py:

def group_edit(request, group_id):
    group_form = GroupFormEdit(instance=Group.objects.get(id=group_id))

    if request.method == "POST":
        group_form = GroupForm(request.POST, instance=Group.objects.get(id=group_id))

        if group_form.is_valid():
            group_form.save()
            messages.success(request, 'Group saved')  # message for inform user of success - See messages in html file
            return redirect('home')
    else:
        group_form = GroupForm()

    return render(request, 'imports/group_edit.html', {
        "group_form": group_form,
    })

我的 group_list.html:

{% block page %}

            <div class="panel-body">
             <table class="table table-bordered table-hover table-striped col-md-3">
                <thead class="thead-dark">
                    <tr class="text-center">
                        <th>Group Name</th>
                        <th>Parent Name</th>
                    </tr>
                </thead>

                <tbody>

                    {%  for group in groups %}
                        <tr>
                            <td scope="row" class="col-md-3"><a href="{% url 'group-edit' group.group_id %}">{{ group.group_name }}</a></td>
                            <td class="col-md-3">{{  group.groupParent_id }}</td>
                        </tr>

                    {%  endfor %}

                </tbody>
             </table>

            </div>

{% endblock %}

我的 urls.py:

urlpatterns = [
    path('', views.imports_last, name='home'),
    path('company_create/', views.company_create, name='company_creation'),
    path('group_create/', views.group_create, name='group_creation'),
    path('group_edit/', views.group_edit, name='group_edit'),
    path('group_list/', views.group_list, name='group_list'),
]

和models.py:

class Group(models.Model):
    group_id = models.AutoField(primary_key=True)
    groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='Parent', on_delete=models.CASCADE)
    group_name = models.CharField(max_length=100, null=False, blank=False, unique=True)

    def __str__(self):
        return '{}'.format(self.group_name)

标签: django

解决方案


我找到了我的痛点;我应该在 url 中提到我想添加一个变量:

path('group_edit/<int:group_id>/', views.group_edit, name='group-edit'),

推荐阅读