无法将上下文传递到主视图

时间:2019-02-20 05:45:24

标签: python django

我一直试图添加一个like按钮,当用户单击该按钮时,该按钮会更改为unlike,但是该按钮没有更改,因为我无法将上下文传递给{ {1}}文件。我知道我使用的逻辑会引发错误,因为home.html不会从服务器接收到ID,但是如果我将参数get_object_or_404()传递给id函数,它也会引发错误因为服务器未向页面提供home()。很抱歉提出一个与逻辑而不是概念有关的问题,但是我无法理解我可以在此处使用哪个概念

views.py

id

models.py

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



def home(request):
    post=get_object_or_404(Blog,id=id)
    context={
    'posts':Blog.objects.all(),
    'is_liked':post.likes.filter(id=request.user.id).exists()
    }
    return render(request,'blog-home',context)
def like_post(request, blog_id):
    post = get_object_or_404(Blog, id=blog_id)
    is_liked=False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        is_liked=False
    else:
        post.likes.add(request.user)
        is_liked=True
    context={
    'is_liked':is_liked
    }   
    return HttpResponseRedirect(Blog.get_absolute_url(blog_id))

def post_detail(request, id):
    post=get_object_or_404(Blog, id=id)

    context={
        'post':post,
        'is_liked': post.likes.filter(id=request.user.id).exists(),
        }
    return render(request, 'blog/post_detail.html',context)








def check_liked(request):
    post = get_object_or_404(Blog, id=blog_id)
    is_liked=False
    if post.likes.filter(id=request.User.id).exists():
        is_liked=True
    else:
        is_liked=False
    context={
    'is_liked':is_liked
    }
    return render(request, 'blog/post_detail.html',context)

urls.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

    def get_absolute_url(blog_id):
        return reverse('post-detail',args=[str(blog_id)])

home.html

from django.urls import path
from . import views 

urlpatterns=[
path('',views.home,name='blog-home'),
path('<int:blog_id>/like/', views.like_post, name='like_post'),
path('post/<int:id>/', views.post_detail, name='post-detail'),
]

post_detail.html

{% 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><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.content }}</p>
          </div>
          <div>
            <form action="{% url 'like_post' post.id %}">
              {% csrf_token %}
              <form action="{% url 'is_liked' %}">
              {% if is_liked %}
                  <button type='submit' name='blog_id' value="{{ post.id }}" class="btn btn-danger">Unlike</button>
              {% else %}
                  <button type='submit' name='blog_id' value="{{ post.id }}" class="btn btn-primary">Like</button>
              {% endif %}
              </form>
            </form>
          </div>
        </article>
{% endfor %}
{% endblock %}

1 个答案:

答案 0 :(得分:0)

您可以使用ajax获得所需的功能。在home.html中,您可以进行以下更改:

{% 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><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
        <p class="article-content">{{ post.content }}</p>
      </div>
      <div>
          <button type='button' onclick="change_status(this)" id="{{post.id}}" name='blog_id' value="{{ post.id }}" class="btn btn-primary"></button>
      </div>
    </article>
{% endfor %}
{% endblock %}

<script>
function change_status($this){
var request_data = $this.id;
console.log("data: " + request_data);
$.post({
    url: "url that leads to your view",//url to like_post in your case(pass the request_data value in the url as the url needs the post id)
    data : { request_data: request_data},
    success : function(json) {
        if(data.is_liked == True){ //perform a check of returned data(dont know actual implementation but you can google it)
        document.getElementByName('blog_id').innerHTML = "Unlike"   }
        else{
             document.getElementByName('blog_id').innerHTML = "Like"  
        }
    }
})}
</script>

可以通过类似的方式来实现该功能,但是您可能需要对其进行一些更改。