找不到Django,URL和视图

时间:2018-11-26 00:05:10

标签: django django-views url-pattern

我正在使用Django 2.1并测试views.py和urls.py 我不明白的是为什么为什么每次输入URL http://127.0.0.1:8000/blog/post_list都会收到404错误消息

我最喜欢的urls.py:

from django.urls import path
from django.contrib import admin
from django.conf.urls import include, url
from organizer import urls as organizer_urls
from blog import urls as blog_urls

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(organizer_urls)),
    path('tag/', include(organizer_urls)),
    path('startup/', include(organizer_urls)),
    path('blog/', include(blog_urls))
]

我的应用程序的urls.py

from django.urls import path
from blog.views import post_list, post_detail

urlpatterns = [
    path('',
        post_list,
        name='blog_post_list'),
    path(
        '<int:year>/<int:month>/<slug:slug>',
        post_detail,
        name='blog_post_detail'),
]

我的应用程序的views.py:

from django.shortcuts import render, get_object_or_404
from .models import Post
# Create your views here.

def post_list(request):
    return render(
        request,
        'blog/post_list.html',
        {'post_list':Post.object.all()}
    )

def post_detail(request, year, month, slug):
    post = get_object_or_404(
        Post,
        pub_date__year=year,
        pub_date__month=month,
        slug=slug)
    return render(
        request,
        'blog/post_detail.html',
        {'post': post})

错误消息是:

  

使用suorganizer_project.urls中定义的URLconf,Django尝试了   这些网址格式,顺序如下:

     

admin /标签/ tag_list [name ='organizer_tag_list']标签//   startup / startup_list [name ='organizer_startup_list']启动//   [name ='organizer_startup_detail']标签/启动/博客/空路径   与这些都不匹配。

为什么?网址在那里:

path('',
        post_list,
        name='blog_post_list'),

这将使我进入post_list视图:

def post_list(request):
    return render(
        request,
        'blog/post_list.html',
        {'post_list':Post.object.all()}
    )

并返回对Post --Post.object.all()-?

中所有对象的查询

我不明白我所缺少的,将感谢您的帮助! :)

1 个答案:

答案 0 :(得分:0)

post_list不在您的URL模式中,而是您的函数名。如果您以这种方式访问​​该网址:127.0.0.1:8000/blog/将起作用,并根据此模式调用post_list()视图

path('',
    post_list,
    name='blog_post_list'),

如果您想使用自己的URL,只需通过添加post_list字符串以以下方式编辑模式即可。

path('post_list',
    post_list,
    name='blog_post_list'),