我有一个喜欢的按钮,我希望它显示一个已经喜欢的按钮,如果用户已经喜欢的职位。这是我的html:
{% for post in posts %}
<div class="border-solid border-2 mr-10 ml-10 mt-3 px-2 pb-4">
<h1 class="text-2xl font-bold mt-2 mb-2"><a href="/user/{{post.User}}">{{post.User}}</a></h1>
{% if post.User == request.user.username %}
<button id="btn_{{post.id}}" type="submit">Edit</button>
<div id="text_{{post.id}}" class="hidden">
<textarea required="" maxlength="300" class="border-solid border-2 w-full h-20" name="text" id="textarea_{{post.id}}" cols="30" rows="10">{{post.Content}}</textarea>
<button id="btn1_{{post.id}}" class="bg-blue-600 rounded-lg px-4 py-2 mt-1 text-white">Confirm</button>
</div>
<script>
document.querySelector('#btn_{{post.id}}').addEventListener('click', function() {
document.querySelector('#Content_{{post.id}}').className = "hidden";
document.querySelector('#text_{{post.id}}').className = 'block';
})
document.querySelector('#btn1_{{post.id}}').addEventListener('click', function() {
fetch('/edit/{{post.id}}', {
method: "POST",
body: JSON.stringify({
content: document.querySelector('#textarea_{{post.id}}').value
})
})
.then(response => response.json())
.then(result =>
document.querySelector('#p_{{post.id}}').innerHTML = result.Content
);
document.querySelector('#Content_{{post.id}}').className = "block";
document.querySelector('#text_{{post.id}}').className = 'hidden';
})
</script>
{% endif %}
<div id="Content_{{post.id}}">
<p id="p_{{post.id}}" class="text-xl">{{post.Content}}</p>
<input id="" type="hidden" value="{{post.Content}}">
</div>
<p>{{post.Date}}</p>
{% if post.User != request.user.username %}
<button id="btn3_{{post.id}}"> like
</button>
<script>
document.querySelector('#btn3_{{post.id}}').addEventListener('click', function() {
fetch('/like/{{post.id}}', {
method: "post",
})
.then(response => response.json())
.then(result =>
document.querySelector('#likes_{{post.id}}').innerHTML = result.likes
);
})
</script>
{% endif %}
{% if post.id in has_liked %}
<button class="btn4_{{post.id}}"> Unlike
</button>
{% endif %}
<p id="likes_{{post.id}}">{{post.likes}}</p>
</div>
{% endfor %}
下面是views.py函数:
def index(request):
if request.method == "POST":
text = request.POST['text']
user = request.user.username
now = datetime.now()
time = now.strftime("%d/%m/%Y %H:%M:%S")
Post.objects.create(
User = user,
Content = text,
Date = time,
likes = 0
)
return redirect("/")
p = Paginator(Post.objects.all().order_by("id").reverse(), 10)
posts = p.get_page(request.GET.get('page'))
likes = Like.objects.all()
has_liked = []
try:
for like in likes:
if like.user == request.user.username:
has_liked.append(like.post)
except:
has_liked = []
return render(request, "network/index.html", {
"posts": posts,
"has_liked": has_liked
})
我试着检查has_liked的值,它返回'1',而www.example.com的值post.id返回1。所以我不知道出了什么问题,因为两个值都是一样的,除了一个是字符串。
1条答案
按热度按时间gcmastyq1#
python中的String和integer值是不一样的。正如你提到的,has_liked返回string '1'和post.id****返回int 1。首先将post.id转换为string。要转换为string,可以使用django内置的模板标签slugify。尝试以下代码: