python - 单击按钮后更改模型字段值
问题描述
我真的知道这是一个常见的话题,但我已经检查了我能找到的每一个解决方案,但它对我不起作用。我想使用按钮单击添加用户点。
视图.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>
我尝试了不同的解决方案,但对我来说没有任何效果。
解决方案
试试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')
推荐阅读
- javascript - 返回元素类 post 表单提交
- javascript - JavaScript:属性函数是否被提升?
- python - 将字符串转换为有序字典
- java - 如何泛化我的界面
- tensorflow - Tensorflow:嵌入式 DSP 的定点量化
- php - 尝试使用 array_unique 和 array_values 从 JSON 数组中删除重复项
- linux - sudo jq 查询权限被拒绝
- android - 缩小 Google Maps API 默认标记
- corda - 如何在 Corda 中获取交易历史记录?
- php - password_verfiy() 使用正确的凭据返回 false