如何在Django中正确使用Slug网址?

时间:2019-12-30 18:27:01

标签: python html django url slug

你好,我是Django的新手,我正在尝试建立一个网站。 在管理页面http://127.0.0.1:8000/admin/posts/post/上,我添加了两个帖子,其中一个帖子有一个条目,**第一个条目是第一个,第二个条目是第二个 问题是当我尝试到达http://127.0.0.1:8000/posts/firsthttp://127.0.0.1:8000/posts/second时,它给我一个404错误,并且告诉我**

  

Django使用custom.urls中定义的URLconf,尝试了这些URL   模式,顺序如下:

admin/
posts/ [name='posts_list']
<slug>
     

当前路径,posts / first,与任何这些都不匹配。

这是models.py

from django.db import models
from django.conf import settings
Create your models here.

User = settings.AUTH_USER_MODEL

class Author(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    email = models.EmailField()
    phone_num = models.IntegerField(("Phone number"))

    def __str__(self):
       return self.user.username

class Post(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField()
    slug = models.SlugField()
    image = models.ImageField()
    author = models.OneToOneField(Author, on_delete=models.CASCADE)


    def __str__(self):
        return self.title

这是views.py

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


def posts_list(request):
    all_posts = Post.objects.all()
    return render(request, 
                  "posts/posts_list.html", 
                  context = {"all_posts": all_posts})


def posts_detail(request, slug):
    unique_slug = get_object_or_404(Post, slug = slug)

    return render(request, "posts/posts_detail.html", {"post": unique_slug})

这是urls.py

from django.contrib import admin
from django.urls import path
from posts.views import posts_list, posts_detail
urlpatterns = [
        path('admin/', admin.site.urls),
        path("posts/", posts_list, name = "posts_list"),
        path("<slug>", posts_detail), #, name = "unique_slug"
    ]

这是这些模板: posts_list.html

<!DOCTYPE html>
<html>
    <head>
        <title>
        </title>
    </head>
    <body>
        {{ all_posts }}
    </body>
</html>

post_detail.html

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

2 个答案:

答案 0 :(得分:1)

slug绝不包含斜杠。您的网址似乎以posts/为前缀。因此,您可以使用以下方法更改urls.py

from django.contrib import admin
from django.urls import path
from posts.views import posts_list, posts_detail

urlpatterns = [
    path('admin/', admin.site.urls),
    path('posts/', posts_list, name='posts_list'),
    path('posts/<slug:slug>/', posts_detail, name='unique_slug'),
]

最好添加路径转换器的类型,所以<slug:slug>

您可能想使用django-autoslug [GitHub]根据某个字段自动构建一个子弹。

答案 1 :(得分:0)

您首先在这里犯了两个错误>>>

#您还没有用逗号关闭最后一个括号

{{1}}

您犯的第二个错误是您尚未定义defined的类型,这很重要