NoReverseMatch 使用具有 <str:pk> 的路径

NoReverseMatch using a path that has <str:pk>

我如何将具有 str:pk 的 urls 路径传递到我的视图和模板中,我想将用户重定向到 viewPhoto 模板,但是当我点击阅读更多时,它抛出像这样的错误:找不到 'photo' 的反向。 'photo' 不是有效的视图函数或模式名称。我怎样才能将其传递到我的视图和模板中?

第 url 个:

path('view/<str:pk>/', views.viewPhoto, name='Photo'),
path('like/<str:pk>/', views.like, name='Photo'),

浏览量:

def like(request, pk):
    post = Photo.objects.get(pk=pk)
    liked = False
    like = Like.objects.filter(user=request.user, post=post)
    if like:
        like.delete()
    else:
        like = True
        Like.objects.create(user=request.user, post=post)
    resp = {
        'liked': liked
    }    
    response = json.dumps(resp)
    return redirect('photo')
    return HttpResponse(response, content_type = "application/json")

查看图片查看:

def viewPhoto(request, pk):

    post = get_object_or_404(Photo, id=pk)

    photo = Photo.objects.get(id=pk)

    liked = [i for i in Photo.objects.all() if like.objects.filter(user= request.user, 
    post = i )]
    return render(request, 'photo.html', {'photo': photo, 'post': post, 'liked': liked})

这就是我在主页模板中传递 url 的方式:

<a href="{% url 'Photo' photo.id %}" class="btn btn-outline-primary btn-sm m-1">Read 
More</a>

您可以这样做来避免 url 冲突:

path('view/<int:pk>/', views.viewPhoto, name='view_photo'),
path('like/<int:pk>/', views.like, name='user_likes'),

# this is for the viewPhoto
<a href="{% url 'view_photo' photo.id %}" class="btn btn-outline-primary btn-sm m-1">Read 
More</a>

# Url for the like object, this would actaully help you avoid any form of url conflict 
<a href="{% url 'user_likes' photo.id %}" class="btn btn-outline-primary btn-sm m-1">