【问题标题】:NoReverseMatch: Reverse for '...' not foundNoReverseMatch:未找到“...”的反向
【发布时间】:2018-06-28 17:08:06
【问题描述】:

我想实现 Django REST 框架并相应地改变我的观点。 FBV phase1 改为 CBV DescriptorList

我的模板 phase1.html

{% load rest_framework %}
...
<li><a href="{% url 'szenariohome' projectid %}">Return to Project Overview</a></li>

我在名为 szenario 的应用中的 urls.py

urlpatterns = [
    url(r'^(?P<id>[0-9]+)/szenariohome/$', views.szenariohome, name='szenariohome'),
    url(r'^(?P<id>[0-9]+)/phase1/$', views.DescriptorList.as_view(), name='phase1'),
]

views.py

class DescriptorList (APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'szenario/phase1.html'

    def get(self, request, id):
        descriptor = Descriptor.objects.all()
        serializer = DescriptorSerializer(descriptor, many=True)
        return Response({'serializer': serializer, 'descriptor': descriptor})

@permission_required_or_403('szenario.view_project', (Project, 'id','id'))
def szenariohome(request, id): als links, mitarbeiter, projectleader
    projectname = get_object_or_404(Project, pk=id)
    projectuser =  AbstractUser.objects.filter (workingproject=id)
    projectid = id
    context = {'projectname': projectname,  'projectuser': projectuser, 'projectid': projectid}
    return render(request, 'szenario/szenariohome.html', context)

@permission_required_or_403('szenario.view_project', (Project, 'id','id'))
def phase2(request, id):
    projectname = get_object_or_404(Project, pk=id)
    projectid = id
    context = {'projectname': projectname, 'projectid': projectid}
    return render(request, 'szenario/phase2.html', context)

我收到错误“Reverse for 'szenariohome' with arguments '('',)' not found. 2 pattern(s) denied”。没有该行模板可以工作。 phase2 的模板具有相同的行并且工作正常。出现这个问题是因为我使用了序列化程序还是因为我混合了 CBV 和 FBV?

感谢任何形式的帮助,谢谢。

【问题讨论】:

  • 可能是您忘记了您的应用程序的namespace,请尝试(如果您有命名空间){% url 'namespace:szenariohome' projectid %}。
  • 在模板中添加了{% url 'szenario:szenariohome' projectid %},在urls.py中添加了app_name = 'szenario',没有用。
  • 您不能在模板的 URL 标记中使用 projectid,因为您没有在视图中的任何位置定义 projectid。
  • 是的,这就是问题所在。谢谢。

标签: django django-templates django-rest-framework django-views


【解决方案1】:

错误表示 django 无法解析名称为 szenariohome 和参数为 ''(空字符串)的 URL。看起来 projectid 未设置,因此无法解析 URL。

您是否将正确的id 传递给您的DescriptorList?

另请注意,id 不是 python 中变量名的错误选择,因为它与 builtin function id 冲突。

【讨论】:

  • 我在我的视图中添加了projectid = id,在回复中添加了'projectid': projectid,修复了错误,谢谢!
猜你喜欢
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 2013-10-05
  • 2018-06-07
  • 2018-09-08
  • 2013-12-22
  • 2018-04-21
相关资源
最近更新 更多