设置URL以使用Slug代替ID

时间:2019-08-05 22:01:32

标签: django

我希望我的URL带有塞子而不是Django中的帖子ID

这是我的urls.py

from django.urls import path, re_path
from blog.views import( 
    blog_post_detail_view, 
    blog_post_list_view,
    blog_post_update_view,
    blog_post_delete_view,)

urlpatterns = [ 
    path('', blog_post_list_view),
    path('<str:slug>/', blog_post_detail_view),
    path('<str:slug>/edit/', blog_post_update_view),
    path('<str:slug>/delete/', blog_post_delete_view), ] 

    models.py

from django.shortcuts import render, get_object_or_404
from django.http import Http404
from .models import BlogPost


def blog_post_list_view(request):
    qs = BlogPost.objects.all()
    template_name = 'blog_post_list.html'
    context = {'object_list': qs}
    return render(request, template_name, context)


def blog_post_create_view(request):
    template_name = 'blog_post_create.html'
    context = {'form': None}
    return render(request, template_name, context)


def blog_post_detail_view(request, slug):
    obj = get_object_or_404(BlogPost, slug=slug)
    template_name = 'blog_post_detail.html'
    context = {"object": obj}
    return render(request, template_name, context)


def blog_post_update_view():
    obj = get_object_or_404(BlogPost, slug=slug)
    template_name = 'blog_post_update.html'
    context = {"object": obj, 'form': None}
    return render(request, template_name, context)

def blog_post_delete_view():
    obj = get_object_or_404(BlogPost, slug=slug)
    template_name = 'blog_post_delete.html'
    context = {"object": obj}
    return render(request, template_name, context

我希望该网址读取http://127.0.0.1:8000/admin/blog/blogpost/i-need-this/change/而不是http://127.0.0.1:8000/admin/blog/blogpost/3/change/

1 个答案:

答案 0 :(得分:0)

首先,您需要通过以下步骤向模型添加slug字段并为post_details模型创建一个绝对URL:

 class BlogPost(models.Model):
    slug = models.SlugField(null=True, max_length=40,unique_for_date='publish')


  from django.urls import reverse

    def get_absolute_url(self):
    return reverse('blog:post_details',args = [
        self.slug,
    ])

“博客”是您的应用名称,“ post_details”是您views.py文件中的详细信息视图功能 现在,将您的应用名称添加到urls.py文件中

 app_name = 'your-app-name'

更改详细信息视图的网址路径

path('<slug:post>/',views.post_details, name = 'post_details'),

':post'是您的函数参数。