A
A
Alexander Zakharov2021-11-18 04:56:08
Django
Alexander Zakharov, 2021-11-18 04:56:08

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})


My urls:
urlpatterns = [
 path('post/<int:pk>/', views.post_detail, name='post_detail'),
 path('post/<int:pk>/', views.best_post, name='best_post')
]

my base.html:
...
{% 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>
...


models.py:
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()


As I understand it - Where I placed the "Best Post" button, There is no b_post variable, So I tried to place it in post_list.html, inside and outside the loop with the output of posts. If I placed them inside the loop, then they worked like regular links to the post. That is, they were useless. And if outside the loop - there was the same problem. I read about similar problems, I found out that you can replace b_post with something, but I still don’t understand what ... The error itself:
NoReverseMatch at /menu/post_list
Reverse for 'best_post' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/$']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sanya Hihi Haha, 2021-11-18
@ValarMayar

And why do you have 2 views serving 1 url?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question