找不到/反向的'like_post'与参数'('',)'的NoReverseMatch。尝试了1个模式:['(?P [0-9] +)/喜欢/ $']

时间:2019-02-18 09:43:28

标签: python django

  

/

处的NoReverseMatch      

找不到带有参数'('',)'的'like_post'的反向。 1个图案    尝试过的:['(?P [0-9] +)/ like / $']


我怀疑我的表格存在问题,但我无法确切指出出什么问题


views.py

from django.shortcuts import render,get_object_or_404
from django.views.generic import ListView
from .models import Blog

class BlogsList(ListView):
    model=Blog
    template_name='blog/home.html'
    context_object_name='blogs'
    ordering=['-date_posted']



def like_post(request, blog_id):
    post = get_object_or_404(Blog, id=blog_id)
    post.likes.add(request.user)
    return HttpResponseRedirect(Blog.get_absolute_url())

models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse 

class Blog(models.Model):
    title=models.CharField(max_length=100)
    content=models.TextField()
    date_posted=models.DateTimeField(default=timezone.now)
    author=models.ForeignKey(User, on_delete=models.CASCADE)
    likes=models.ManyToManyField(User,related_name='likes',blank=True)
    def __str__(self):
        return self.title

urls.py

from django.urls import path
from . import views 

urlpatterns=[
path('',views.BlogsList.as_view(),name='blog-home'),
path('<int:blog_id>/like/', views.like_post, name='like_post')
]

html代码

{{ user.username }}
{% block content %}
    {% for post in blogs %}
        <article class="media content-section">
          <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
          <div class="media-body">
            <div class="article-metadata">
              <h2>{{ post.author }}</h2>
              <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
            </div>
            <h2>{{ post.title }}</h2>
            <p class="article-content">{{ post.content }}</p>
          </div>
          <div>
            <form action="{% url 'like_post' blog_id %}">
              {% csrf_token %}
              <button type='submit' name='blog_id' value="{{ blog_id}}" class="btn btn-primary">Like</button>
            </form>
          </div>
        </article>
{% endfor %}
{% endblock %}

1 个答案:

答案 0 :(得分:1)

在模板中,blog_id未定义(是否提供上下文?)。

您应将blog_id更改为post.id

<form action="{% url 'like_post' post.id %}">
  {% csrf_token %}
  <button type='submit' name='blog_id' value="{{ post.id }}" class="btn btn-primary">Like</button>
</form>