无法在模板 Django 中反转 url

Cannot reverse url in template Django

我被 custom-text-form.html 文件中的反向 url 名称卡住了。

这是我的custom-text-form.html

{% load rest_framework %}
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<html>
    <body>
        <form class="form-horizontal" action="{% url 'tool:custom-text' %}" method="POST" novalidate>
            {% csrf_token %}
            {% render_form serializer template_pack='rest_framework/horizontal' %}
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-default">Submit</button>
                </div>
            </div>
        </form>
    </body>
</html>

configs/urls.py.

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls import url
from django.views.static import serve
from django.contrib.staticfiles.urls import staticfiles_urlpatterns


urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^run/media/(?P<path>.*)$', serve,
        {'document_root': settings.MEDIA_ROOT, }),
    path('api/', include('apps.tool.urls'))
]

urlpatterns += staticfiles_urlpatterns()

tool/urls.py.

from django.urls import path, include
from django.conf.urls import url
from rest_framework.routers import SimpleRouter

from .views import CustomTextViewSet, UploadImageViewSet, FormCustomTextView

app_name = 'tool'

router = SimpleRouter(trailing_slash=False)
router.register('upload-image', UploadImageViewSet)
router.register('custom-text', CustomTextViewSet)

urlpatterns = [
    path('', include(router.urls), name='custom-text'),
    url('form-custom-text', FormCustomTextView.as_view())
]

我遇到了这个错误 NoReverseMatch at /api/form-custom-text 尝试请求时 url http://localhost:8000/api/form-custom-text error

我的TEMPLATES配置

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(PROJECT_ROOT, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

我的文件夹结构: img1 img2

我试图在 tool/url.py 中添加 namespace='tool',但仍然无法正常工作。

任何人都可以提供帮助!! 谢谢

改变你的configs/urls.py

....

urlpatterns = [
    ....,
    path('api/', include(('apps.tool.urls', 'tool'), namespace='tool'))
]

urlpatterns += staticfiles_urlpatterns()

因为 Django > 2.0 使用 Path 你需要指定 app_namenamespace

建议:尽量使用django-extension。已经注册了许多有用的命令。您可以使用 python manage.py show_urls 显示完整的 urls 架构包括 namespacename of url