【问题标题】:Page not foung 404 error - Slug id not displaying (found) : http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily找不到页面 404 错误 - Slug id 未显示(找到):http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily
【发布时间】:2021-06-13 11:37:38
【问题描述】:

先生,我正在用 Django 开发一个 slug 项目。当我尝试打印 slug id 帖子时,它不会显示 404 错误。试了n次。任何人,请帮我在 urls.py 中解决这个问题。

找不到页面 (404) 请求方法:GET 请求网址:http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily 使用 postcommentpro.urls 中定义的 URLconf,Django 按以下顺序尝试了这些 URL 模式:

管理员/ postcommentapp/(?P\d+)/(?P[\w-]+)/$ [name='post_detail'] 当前路径,postscommentapp/6/how-learn-anything-very-easily,与其中任何一个都不匹配。

models.py

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Post(models.Model):
    STATUS_CHOICES = (
            ('draft', 'draft'),
            ('published', 'published')
        )
    title = models.CharField(max_length=50)
    slug = models.CharField(max_length=50)
    author = models.ForeignKey(User, on_delete = models.CASCADE)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')

    def __str__(self):
        return self.title

admin.py

from django.contrib import admin
from .models import Post
# Register your models here.

class AdminPost(admin.ModelAdmin):
    list_display = ['title', 'slug', 'body', 'author', 'created', 'updated', 'status']
    prepopulated_fields = {'slug':('title',)}
    list_editable = ('status',)
admin.site.register(Post, AdminPost)

views.py

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

def post_List(request):
    posts = Post.objects.all()
    return render(request, 'postscommentapp/post_list.html', {'posts':posts})

def post_detail(request, id, slug):
    post = Post.objects.get(id=id)
    return render(request, 'postscommentapp/post_detail.html', {'post':post})

url.py - 帖子评论应用

from django.urls import path
from postscommentapp import views

urlpatterns = [
    path('', views.post_List, name=''),
    path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]

urls.py

"""postscommentpro URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

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

post_detail.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<h2>{{ post.title }}</h2>
</body>
</html>

post_list.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <!-- Bootstrap CDN Lines -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&display=swap" rel="stylesheet">
</head>
<style>
    .col-md-6{
        text-align: justify;
    }
    .img-thumbnail{
        border:1px solid #6b6b47;
    }
    .title{
        font-family: 'Poppins', sans-serif;
    }
</style>
<body style="font-family: 'Poppins', sans-serif;">
<div class="container-fluid">
    <br>
    <h2 class="text-center" style="font-weight:bold; color: #0040ff;">Post Comments Python/Django Project:</h2>
    <div class="row">
        {% for each_item in posts %}
            <div class="col-md-6">
                <br>
                <div class="img-thumbnail">
                ⭐ <a href="#" class="title">{{ each_item.title }}</a><small style="float:right">{{ each_item.created }}</small><br>
                ➟ Author: {{ each_item.author }}<br><br>
                {{ each_item.body }}<br>
                </div>
                <br>
            </div>
        {% endfor %}
    </div>
</div>
</body>
</html>

【问题讨论】:

  • 在 URL 的末尾添加一个斜线`/
  • 在 URL 末尾尝试了 /。但是,找不到显示的 slug id 帖子页面。再次找不到相同的错误页面。 @WillemVanOnsem 先生。

标签: django django-urls slug


【解决方案1】:

我以自己的方式解决了这个错误。在 urls.py 帖子评论应用中

from django.urls import path
from postscommentapp import views

urlpatterns = [
    path('', views.post_List, name=''),
    path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]

将此 url 代码更改为此 urls.py - postcommentapp

 from django.urls import path
    from postscommentapp import views
    
    urlpatterns = [
        path('', views.post_List, name=''),
        path('post/<int:id>/<slug:slug>/', views.post_detail, name='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):
    posts = Post.objects.all()
    return render(request, 'postscommentapp/post_list.html', {'posts':posts})

def post_detail(request, id, slug):
    # post = Post.objects.get(id=id)
    post = get_object_or_404(Post, id=id, slug=slug)
    return render(request, 'postscommentapp/post_detail.html', {'post':post})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2019-08-14
    • 2020-10-25
    • 2016-10-30
    • 1970-01-01
    • 2017-06-01
    相关资源
    最近更新 更多