当前正在阅读Eric Matthes撰写的Python速成课程,我正在尝试使用python和Django编写一个简单的学习方法,但是当我尝试输入主题URL时,我总是遇到错误。该错误似乎来自base.html(模板),它表示learning_logs不是注册的名称空间,即使我将其编写为名为app_name的变量并将其包含在URL中。
这是代码:
主要 urls.py:
from django.contrib import admin
from django.urls import path , include , re_path
app_name = 'learning_logs'
urlpatterns = [
path('admin/', admin.site.urls),
path('' , include(("learning_logs.urls", app_name ) ))
]
urls.py:
from django.urls import path , re_path
from . import views
app_name = 'learning_logs'
urlpatterns = [
#Home page
path('', views.index, name='index'),
path('topics/', views.topics , name='topics'),
re_path(r'^topics/(?P<topic_id>\d+)/$' , views.topic , name = 'topic'),
re_path(r'^new_topic/$' , views.new_topic , name = 'new_topic'),
re_path(r'^new_entry/(?P<topic_id>\d+)/$' , views.new_entry , name = 'new_entry'),
]
base.html:
<p>
<a href="{% url 'learning_logs:index' %}">Learning Log</a>
<a href="{% url 'learning_logs:topics' %}">Topics</a>
</p>
{% block content %}
{% endblock content %}
错误:
答案 0 :(得分:0)
我认为您需要通过删除app_name
并修复包含内容来修复主要 urls.py 中的声明。
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('' , include('learning_logs.urls'))
]
答案 1 :(得分:0)
只需将主urls.py
文件修复如下:
from django.contrib import admin
from django.urls import path , include , re_path
urlpatterns = [
path('admin/', admin.site.urls),
path('' , include(("learning_logs.urls", app_name='learning_logs') ))
]
请注意app_name=
中的命名参数include