根据模型中的值创建URL

时间:2019-05-26 21:30:17

标签: python django

我想创建一个博客页面,它可以正常工作,但是我想更改特定博客文章的URL。目前,指向特定博客帖子的URL为 myurl.com/blog/pk ,但我希望改为 myurl.com/blog/category/title 。我怎样才能做到这一点?如果您愿意,也请对代码进行任何形式的批评。

Models.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=20)

class Post(models.Model):
    title = models.SlugField(max_length = 250, null = True, blank = True)
    body = models.TextField()
    created_on = models.DateTimeField(null=True)
    last_modified = models.DateTimeField(null=True)
    categories = models.ManyToManyField('Category', related_name='posts')

class Comment(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)

Views.py

from django.shortcuts import render
from .models import Post
from .models import Comment
from .forms import CommentForm
from django.http import HttpResponse


def blog_index(request):
    posts = Post.objects.all().order_by('-created_on')
    context = {
        "posts": posts,
    }
    return render(request, "blog_index.html", context)


def blog_category(request, category):
    posts = Post.objects.filter(
        categories__name__contains=category
    ).order_by(
        '-created_on'
    )
    if not posts:
        return HttpResponse(status=404)

    context = {
        "category": category,
        "posts": posts
    }
    return render(request, "blog_category.html", context)


def blog_detail(request, pk):
    post = Post.objects.get(pk=pk)

    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }
    return render(request, "blog_detail.html", context)

应用urls.py

from django.urls import path
from . import views

urlpatterns = [
    path("", views.blog_index, name="blog_index"),
    path("<int:pk>/", views.blog_detail, name="blog_detail"),
    path("<category>/", views.blog_category, name="blog_category"),
]

项目URL

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

1 个答案:

答案 0 :(得分:0)

我非常确信您要使用标题。标题通常可以包含空格(),标点符号(~!#.?等)和特殊字符。 URL不能包含大多数这些字符。的确可以逃脱这些字符,但是URL看起来很丑:

myurl.com/some%20title%20containing%20spaces

现在这不是很可读。

但是,您可以将 slug SlugField [Django-doc]一起使用。 SlugFieldCharField,但是它做了一些清理工作以避免URL难看。例如,'some title containing spaces'将转换为some-title-containing-spaces

您可以将SlugField添加到CategoryModel中,例如:

from django.utils.text import slugify

class Category(models.Model):
    name = models.CharField(max_length=20)
    slug = models.SlugField(unique=True, blank=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super().save(*args, **kwargs)

urlpatterns中,我们可以将slug指定为:

# app/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.blog_index, name='blog_index'),
    path('<int:pk>/', views.blog_detail, name='blog_detail'),
    path('category/<slug:category_slug>/', views.blog_category, name='blog_category'),
]

然后我们可以在子弹视图中进行过滤:

from django.shortcuts import get_list_or_404
from .models import Post

def blog_category(request, category_slug):
    posts = get_list_or_404(Post.objects.filter(
        categories__slug=category_slug
    ).order_by(
        '-created_on'
    ))

    context = {
        'category': category,
        'posts': posts
    }
    return render(request, 'blog_category.html', context)

生成独特的子弹

有时slug已经存在于另一个Category对象中,我们可以使用脚本生成唯一的子段,例如:

from django.utils.text import slugify
from itertools import count

class Category(models.Model):
    name = models.CharField(max_length=20)
    slug = models.SlugField(unique=True, blank=True)

    def save(self, *args, **kwargs):
        for i in count():
            slug = slugify('{}{}'.format(self.title, i or ''))
            if not Category.objects.filter(slug=slug).exists():
                break
        self.slug = slug
        super().save(*args, **kwargs)