如何从Django模型中减去?



我试图从Django模型的IntegerField的值中添加和减去1,并在网页上显示它,这取决于何时单击按钮。

models.py

class User(AbstractUser):
following = models.ManyToManyField("self", related_name="followers", symmetrical=False)
following_num = models.IntegerField(default=0)

在views.py:

添加:following_num = page_visitor.following_num +1

减去:following_num = page_visitor.following_num -1

显示在html中应该显示数字的地方:

<django.db.models.query_utils.DeferredAttribute object at 0x0000022868D735E0>

整个视图:

def username(request, user):
#get user
user = get_object_or_404(User.objects, username=user)
posts = Post.objects.filter(user=user).order_by('-date_and_time')
page_visitor = get_object_or_404(User.objects, username=request.user)
if user == request.user:
followButton = False
else:
followButton = True
if request.method == "POST":
if "follow" in request.POST:
request.user.following.add(user)
following_num = page_visitor.following_num +1
#following_num = F('User.following_num') + 1
elif "unfollow" in request.POST:
request.user.following.remove(user)
following_num = page_visitor.following_num -1
#following_num = F('User.following_num') - 1
followers_num = page_visitor.following_num
following_num = User.following_num
return render(request, "network/username.html",{
"user": user,
"posts": posts,
"followButton": followButton,
"followers": followers_num,
"following": following_num
})
html

{% block body %}
<h1>{{ user }}</h1>
<h4>Followers:{{ followers }}</h4>
<h4>Following:{{ following }}</h4>
<!--follow/unfollow button-->
{% if followButton == True %}
<form action = "{% url 'username' user %}" method = "POST">
{% csrf_token %}
{% if user not in request.user.following.all %}
<input type="submit" value="Follow" name="follow">
{% else %}
<input type="submit" value="Unfollow" name="unfollow">
{% endif %}
</form>
{% endif %}

<!--displays all the posts-->
{% for post in posts %}
<div class = "individual_posts">
<a href="{% url 'username' post.user %}"><h5 class = "post_user">{{ post.user }}</h5></a>
<h6 id = "post_itself">{{ post.post }}</h6>
<h6 class = "post_elements">{{ post.date_and_time }}</h6>
<h6 class = "post_elements">{{ post.likes }} Likes</h6>
</div>
{% endfor %}
{% endblock %}

你引用的是类(model)而不是对象(instance)

following_num =User.following_num

因为你已经把你的user对象传递给了模板,所以你也可以直接访问属性{{user.following_num }} {{request.user.following_num }}

,但你最好重命名传递的用户变量,以避免混淆/错误

获取django模板中的用户信息

没有html,应该显示的数字,我不能告诉为什么它显示,但如果你打算改变下面的计数,然后你需要调用page_visitor.save()后改变page_visitor的属性,以便它保存在数据库中的新属性的值

相关内容

  • 没有找到相关文章

最新更新