首页 > 解决方案 > 我想向 django html 中的按钮添加一个函数,这样当我单击该按钮时,它会将 +1 添加到现有数据

问题描述

[在此处输入图像描述][1]```py def bunk(响应):

def add_attend(x):
    x = x + 1

if response.method == 'POST':
    boonk = Bunk_calc(response.POST)
    if boonk.is_valid():
        class_attend = int(boonk.cleaned_data['class_attend'])
        total_attend = int(boonk.cleaned_data['total_attend'])
        subject = boonk.cleaned_data['subject']
        t = Bunk(class_attend=class_attend, total_attend=total_attend, subject=subject)
        min_attend = ceil(total_attend*0.75)
        percentage = (class_attend/total_attend)*100
        add_attend(class_attend)
        t.save()

我想将此 def add_attend 链接到我的按钮。我怎样才能做到这一点?

我想将此 def add_attend 链接到我的按钮。我怎样才能做到这一点?我想在添加按钮旁边创建一个按钮“+1”,它将 +1 添加到现有的 class_attend

标签: djangodjango-modelsdjango-formsdjango-templatesdjango-views

解决方案


您正在尝试通过 Jinja 实现加法,最好在这种情况下使用自定义模板标签。在你的 Django App 下创建一个 templatetags 目录并添加一个 custom_tags.py 文件。在 custom_tags.py 中编写代码:

@register.filter()
def add_attend(x):
    x = x + 1
    return x

在您的 HTML 中,首先加载自定义标签:

{% load custom_tags %}

然后,您可以在需要时适当地使用自定义标签,例如:

{{ 1|add_attend }}

推荐阅读