Добавить тег Title или Title к пути url
Я надеюсь, что кто-нибудь сможет помочь мне с этой проблемой. У меня проблемы с добавлением заголовка моей страницы/статьи в url путь. Я пробовал несколько способов, но никак не могу добиться этого. Если кто-нибудь может помочь, это было бы здорово.
Мой текущий путь Url - "https://stackoverflow.com/article/1"
Хотелось бы, чтобы это был "https://stackoverflow.com/article/1/example-question-help", или какая-то его вариация.
Ниже вы можете увидеть, как настроены мои представления и url файлы.
path('article/<int:pk>/', ArticleDetailView.as_view(), name='article-detail'),'
class ArticleDetailView(DetailView):
model = Post
template_name = 'article_detail.html'
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = stuff.total_likes()
liked = False
if stuff.likes.filter(id=self.request.user.id).exists():
liked = True
context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
context["total_likes"] = total_likes
context["liked"] = liked
return context
Предполагая, что ваша модель имеет поле slug, называемое slug
, что, похоже, возможно, учитывая ваш запрос, вы измените все следующим образом;
path('article/<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'),'
Django сделает все остальное, потому что SingleObjectMixin
, который используется DetailView
, просматривает URL сначала для первичного ключа, затем для slug.
Таким образом, это даст вам URL, которые выглядят следующим образом;
https://stackoverflow.com/article/example-question-help
Вы можете определить путь, который включает в себя как первичный ключ, так и slug:
path(
'article/<int:pk>/<slug:slug>/',
ArticleDetailView.as_view(),
name='article-detail',
),
This will automatically filter the item properly. You can boost efficiency by determining the number of likes and whether the object is liked all in the same queryset with an Exists
subquery [Django-doc]:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count, Exists, OuterRef
class ArticleDetailView(LoginRequiredMixin, DetailView):
model = Post
template_name = 'article_detail.html'
queryset = Post.objects.annotate(total_likes=Count('likes'))
def get_queryset(self, *args, **kwargs):
super().get_queryset(*args, **kwargs).annotate(
is_liked=Exists(
Post.likes.through.objects.filter(
post_id=OuterRef('pk'), user=request.user
)
)
)
def get_context_data(self, *args, **kwargs):
return super().get_context_data(
*args, **kwargs, cat_menu=Category.objects.all()
)
In the modeling, you might want to work with an AutoSlugField
[readthedocs.io] from the django-autoslug
package [readthedocs.io] to automatically slugify. Otherwise you will have to do this yourself. It also makes not much sense that the slug field is NULLable: normally a record will always have a slug. You thus might want to refactor the model to:
from autoslug import AutoSlugField
from django.conf import settings
class Post(models.Model):
title = models.CharField(max_length=250)
header_image = models.ImageField(null=True, blank=True, upload_to='images/')
title_tag = models.CharField(max_length=250, default='none')
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
slug = models.AutoSlugField(populate_from='title')
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=250, default='')
snippet = models.CharField(max_length=250)
likes = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name='liked_posts'
)
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.