不能在模板中反转网址,Django

问题描述 投票:0回答:1

我被反转的网址名称卡住了 custom-text-form.html 文件。

这是我的 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>

configsurls.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()

toolurls.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 当尝试请求网址时 http://localhost:8000/api/form-custom-text错误

我的 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',
            ],
        },
    },
]

我的文件夹结构。img1img2

我是想加 namespace='tool'tool/url.py 但还是不行。

有谁能帮忙!!!谢谢

django templates url django-rest-framework reverse
1个回答
1
投票

改变你的 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

© www.soinside.com 2019 - 2024. All rights reserved.