首页 > 解决方案 > 单击按钮后更改模型字段值

问题描述

我真的知道这是一个常见的话题,但我已经检查了我能找到的每一个解决方案,但它对我不起作用。我想使用按钮单击添加用户点。

视图.py

 def add_points(request):
        if request.GET.get('mybtn'):
            profil = get_object_or_404(Profile, created_by=request.user)
            profil.points += 10
            profil.save(update_fields=["points"])
            return render(request, 'users/profile.html')

模型.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to="profile_pics")
    points = models.PositiveIntegerField(default=0)
    people = models.PositiveIntegerField(default=0)

.html 文件

<div>
            <form method="POST">
                {% csrf_token %}
            <input type="submit" class="btn" value="+10 pkt" name="mybtn"/>
                </form>
</div>

我尝试了不同的解决方案,但对我来说没有任何效果。

标签: pythondjangodjango-modelsdjango-templatesdjango-views

解决方案


试试F函数。

from django.db.models import F
      def add_points(request):
                if request.GET.get('mybtn'):
                    profil = get_object_or_404(Profile, created_by=request.user)
                    profil.points = F('points') + 10
                    profil.save(update_fields=["points"])
                    return render(request, 'users/profile.html')

推荐阅读