Answer the question
In order to leave comments, you need to log in
How to fix '{'pk': ''}' not found error?
I create a function for the site - "Best post" or something like that. The bottom line is that when clicking on the link, the user should be directed to the article with the largest number of likes.
My views:
def best_post(request, pk):
best_post = Post.objects.annotate(num_likes=Post.total_likes()).filter(num_likes__gt=70).order_by('-created_date')
b_post = get_object_or_404(best_post, pk=pk)
total_likes = b_post.total_likes()
latest_comments_list = Comment.objects.filter(post=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
form = form.save(commit=False)
form.author = request.user
form.post = b_post
form.save()
else:
form = CommentForm()
return render(request, 'blog/post_detail.html', {'best_post': best_post, 'b_post': b_post, 'latest_comments_list': latest_comments_list, 'total_likes': total_likes,
'form': form})
urlpatterns = [
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/<int:pk>/', views.best_post, name='best_post')
]
...
{% block bg %}
<body class="start-pages">
{% endblock %}
<div class="page-header">
{% if user.is_authenticated %}
{% else %}
<a href="{% url 'register' %}" class="top-menu btn btn-outline-primary">Регистрация</a> <a href="{% url 'login' %}?next={% url 'main_menu' %}" class="top-menu btn btn-outline-primary">Войти</a>
{% endif %}
<a href="{% url 'main_menu' %}" class="btn btn-light underhead">Главная</a>
<a href="{% url 'post_new' %}" class="btn btn-light underhead">Добавить пост</a>
<a href="{% url 'best_post' pk=b_post.pk %}" class="btn btn-light underhead"><span class="star">★ </span>Лучший пост</a>
{% if user.is_authenticated %}
<a href="{% url 'logout' %}" class="btn btn-light underhead">Выход</a>
{% endif %}
</div>
...
class Post(models.Model):
GAME_CHOICES = (
(1, 'WOT'),
(2, 'Pubg'),
)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
textinfo = models.CharField(max_length=250, default='О чем ваш текст?')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_post')
game = models.PositiveSmallIntegerField(choices=GAME_CHOICES, default=1)
tags = TaggableManager()
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return '{}/{}/{}'.format(self.title, self.game, self.tags)
def total_likes(self):
return self.likes.count()
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question