编写我的第一个Django应用程序

2024-04-20 08:07:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力学习Django,并在https://docs.djangoproject.com/en/2.0/intro/tutorial03/尝试一步一步的教程。你知道吗

我已经完成了应用程序(好吧,直到第7部分),并按预期工作(并已在教程中解释)。你知道吗

唯一的问题(到目前为止),我面临的是当我试图从“管理”页面导航到链接页面“查看网站”时,我被提出了“页面未找到(404)”错误。为了使情况更清楚,正在附上一张图片。你知道吗

链接指向“http://127.0.0.1:8000/”,而它应该指向“http://127.0.0.1:8000/polls/”。当我在地址栏中添加路径的缺失部分(手动)时,会显示正确的页面(如预期的那样)。你知道吗

我试图搜索这个以及许多其他论坛,但无法得到正确的解决方案。你知道吗

我正在mac sierra上使用Django 2.0.6和Python 3.6.4。你知道吗

我很感激你能提供线索。你知道吗

谢谢

我的网站/网址.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

我的网站/投票/网址.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
    ]

投票/模板/投票/索引.html

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />


{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

Error on navigation at VIEW SITE


Tags: pathdjangonamefromimportviewadmin网站
3条回答

你应该打开http://127.0.0.1:8000/polls/

不是

http://127.0.0.1:8000/。你知道吗

如果您想使用http://127.0.0.1:8000/,那么您的路径应该是

from django.urls import include, path

urlpatterns = [
    path('', include('polls.urls')),
    path('admin/', admin.site.urls),
]

应该是这样的:

path('', include('polls.urls')),

不是这样的:

path('polls/', include('polls.urls'))

因为它应该是你网站的根url

以下是我所做的(可能不是最优雅的解决方案,但效果很好)。你知道吗

我修改了“mysite”/网址.py“文件,如图所示:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('', include('polls.urls')),
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

通过这种方式,我可以从Django管理页面上的“查看站点”链接(url:“127.0.0.1:8000”)以及其他地方的链接(url:“127.0.0.1:8000/polls/”)访问“polls”页面。你知道吗

谢谢你的帮助。你知道吗

另外,访问https://docs.djangoproject.com/en/2.0/topics/http/urls/可能对我这样的学习者有帮助。你知道吗

相关问题 更多 >