如何在不重新加载页面的情况下运行包含操作参数的视图函数

时间:2019-04-14 11:52:50

标签: python ajax django

我正在创建一个网站,允许用户发布评论和喜欢的帖子。我创建了一个视图功能,该功能允许用户喜欢帖子,但不确定如何实现Ajax或类似技术来执行请求而无需重新加载页面。这样用户就不会失去他们在页面上的位置,并且在喜欢帖子后必须向下滚动才能找到它。

在我的views.py中:

#this is the function i wish to run without reloading
def like(request, operation, id):
    like = Post.objects.get(id=id)
    if operation == 'add':
        Like.make_like(request.user, like)
    elif operation == 'remove':
        Like.lose_like(request.user, like)
    return HttpResponseRedirect('/Feed/')

#this is the view in which it is called
class FeedView(TemplateView):
    template_name = 'feed.html'


    def get(self, request):
        form = HomeForm()
        posts = Post.objects.all().order_by('-created')
        users = User.objects.exclude(id=request.user.id)
        try:
            like = Like.objects.get(user=request.user)
            likes = like.posts.all()
        except Like.DoesNotExist:
            like = None
            likes = None
        args = {
            'form': form, 'posts': posts, 'users': users, 'likes': likes
        }
        return render(request, self.template_name, args)

    def post(self, request):
        form = HomeForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()

            text = form.cleaned_data['post']
            form = HomeForm()
            return HttpResponseRedirect('/Feed/')

        args = {'form': form, 'text': text}
        return render(request, self.template_name, args)

feed.html

    {% for post in posts %}
        <p class="name">{{ post.user.username }}</p>
        <h3>{{ post.post }}</h3>
              {% if not post in likes %}
                <li-r><a class="like" href="{% url 'like' operation='add' id=post.id %}"> {{ post.total_likes }}  </a></li-r>
              {% endif %}
              {% if post in likes %}
                <li-r><a class="unlike" href="{% url 'like' operation='remove' id=post.id %}"> {{ post.total_likes }} </a></li-r>
              {% endif %}
        <p class="date">{{ post.created }}</p>
    {% endfor %}

urls.py

    urlpatterns = [
    url(r'^Feed/$', FeedView.as_view(), name='feed'),
    url(r'^like/(?P<operation>.+)/(?P<id>\d+)/$', views.like, name='like')
    ]

我尝试将函数放入Feed类中,但是我不知道如何编写包含"(?P<operation>.+)/(?P<id>\d+)"部分以及该类的URL,即使这样可以解决我的问题。但是我想我可以使用ajax,尽管我不知道怎么做。

1 个答案:

答案 0 :(得分:0)

您需要在此处使用Ajax。在锚点标签上使用matrices事件侦听器进行点赞/点赞,改为进行ajax调用,并根据响应更新计数。

cbind