Django像按钮一样增加并将我重定向到同一页面

时间:2016-03-15 14:37:57

标签: python django

我遇到类似按钮的问题,它根本不起作用。在我使用的模板中 {{ post.likes }}显示喜欢计数和我使用的按钮<a href="{% url 'post_like' pk=post.pk %}" class="btn btn-block hvr-bounce-in">

这是views.py

from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect, render_to_response
from django.template import Context
from django.utils import timezone
from django.views.generic import View

from blog.forms import CommentForm, PostForm, SearchForm
from blog.models import Post


def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')[0:50]
    return render(request, 'blog/index.html', {'posts': posts})


def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})


def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('blog.views.post_detail', pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'blog/add_comment_to_post.html', {'form': form})


def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'blog/add_post.html', {'form': form})


def search_view(request):
    if request.method == "POST":
        search_text = request.POST['search-form']
    else:
        search_text = ''
    posts = Post.objects.filter(title__contains=search_text)
    return render_to_response('blog/search.html', {'post': posts})


def post_like(request, pk):
    if pk:
        post = Post.objects.get(id=pk)
        count = post.likes
        count += 1
        post.likes = count
        post.save()
    return HttpResponseRedirect('post/%s/like/' % pk)


def dislike_post(request, pk):
    if pk:
        post = Post.objects.get(id=pk)
        post.dislikes += 1
        post.save()
    return HttpResponseRedirect('post/%s/like/' % pk)

和urls.py

from django.conf.urls import url

from blog import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
    url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
    url(r'^post/(?P<pk>[0-9]+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),
    url(r'^post/new/$', views.post_new, name='post_new'),
    url(r'^search/$', views.search_view, name='search'),
    url(r'^post/(?P<pk>[0-9]+)/like/$', views.post_like, name='post_like'),
    # url(r'^post/(?P<pk>[0-9]+)/dislike/$', views.dislike_post, name='post_dislike'),
]

编辑:对于model.py,这是我使用的代码:

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=150)
    text = models.TextField()
    created_date = models.DateTimeField(
        default=timezone.now)
    published_date = models.DateTimeField(
        blank=True, null=True)
    image = VersatileImageField(upload_to='images')
    tags = TaggableManager()
    likes = models.IntegerField(default=0)
    dislikes = models.ImageField(default=0)
    views = models.IntegerField(default=0)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

1 个答案:

答案 0 :(得分:2)

要更改视图重定向到的网址,您只需更改传递给HttpResponseRedirect的值即可。

return HttpResponseRedirect('/post/%s/' % pk)

请注意,网址以斜杠开头。您可以使用reverse来防止对网址进行硬编码

from django.core.urlresolvers import reverse

def post_like(request, pk):
    ...
    return HttpResponseRedirect(reverse('post_detail', args=[pk]))    

我不确定为什么likes计数没有增加。在您看来,我会添加一些打印语句来尝试找出正在发生的事情,例如:

from django.shortcuts import redirect

def post_like(request, pk):
    print("In post_like")
    post = Post.objects.get(id=pk)
    print("likes before: ", post.likes)
    post.likes += 1
    post.save()
    print("likes after: ", post.likes)
    return redirect('post_detail', pk=pk)

请注意,我使用了redirect快捷方式来简化代码。您不需要if pk语句,因为pk是必需参数。