具有相似功能的KeyError slug

时间:2017-11-28 17:51:07

标签: python django-views

我正在尝试创建类似的功能。在我的views.py中:

@login_required
def like_post_view(request, *args, **kwargs):
    try:
        post = Posts.objects.get(slug=kwargs['slug'])

        _, created = Like.objects.get_or_create(post=post,user=request.user)

        if not created:
            messages.warning(
                request,
                'You\'ve already liked the post.'
            )
    except Posts.DoesNotExist:
        messages.warning(
            request,
            'Post does not exist'
        )

    return HttpResponseRedirect(
        reverse_lazy(
            'posts:view',
            kwargs={'slug': kwargs['slug']}
        )
    )
# unlike posts
@login_required
def unlike_post_view(request, *args, **kwargs):
    try:
        like = Like.objects.get(
            post__slug=kwargs['slug'],
            user=request.user
        )
    except Like.DoesNotExist:
        messages.warning(
            request,
            'You didn\'t like the post.'
        )
    else:
        like.delete()

    return HttpResponseRedirect(
        reverse_lazy(
            'posts:view',
            kwargs={'slug': kwargs['slug']}
        )
    )

编辑:从评论中添加相关代码:

urlpatterns = [ 
   url(r'^$', views.index,name='index'), 
   url(r'^$', views.homepage,name='home'), 
   url(r'^profiles/$', views.profile,name='profiles'), 
   url(r'^profiles/post', views.posts,name='uploadpost'), 
   url(r'^profiles/edit', views.update_profile,name='editprofile'), 
   url(r'^profiles/like',views.like_post_view,name='posts'), 
   url(r'^profiles/unlike',views.unlike_post_view,name='posts')‌​, 
] if settings.DEBUG: 
      urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) 

0 个答案:

没有答案