Django在temp中使用函数

2024-04-29 05:07:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试找出如何为我的用户创建一个进度跟踪程序,这样他们就可以看到他们填写的表格的百分比

我不知道如何创建函数,然后在模板中使用/调用它

视图-计算进度函数

我的类中的函数现在看起来是这样的(我故意排除类中的窗体以避免混乱):

class OpdaterEvalView(ModelFormMixin, DetailView):
    template_name = 'evalsys/evalueringer/evaluering_forside.html'
    model = Evaluation
    form_class = OpdaterEvalForm

    def calculate_progress(self, evaluation=None):
        value = [evaluation.communication, evaluation.motivate_others,
                 evaluation.development, evaluation.cooperation]
        count = 0
        if value[0]:
            count += 1
        if value[1]:
            count += 1
        if value[2]:
            count += 1
        if value[3]:
            count += 1
        return count * 25

其思想是,它将检查数据库中存在哪些值的数组,如果存在0、1、2、3个值,它将显示25%、50%、75%、100%。我真的不知道如何让这个函数在我的模板中工作?我怎么称呼它?也许函数在课堂之外?但是我怎样才能针对评估的特定pk

更新-更多信息

我有一个评估模型,还有一个叫做关系的模型,其中我有四个值:

 value = [evaluation.eval_relations.communication, evaluation.eval_relations. motivate_others,
                     evaluation.eval_relations.development, evaluation.eval_relations.cooperation]

我有一个评估模型的外键叫做eval\u relations


Tags: 函数模型模板ifvaluecountevalclass
1条回答
网友
1楼 · 发布于 2024-04-29 05:07:59

以下是我的假设:

用户模型

包含5个字段(f1、f2、f3、f4、f5)的纵断面模型和一个包含用户模型的ooneField

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_name')
    f1 = ...
    .
    .

表单中将有5个字段。我们想显示数据库中保存了多少字段

当用户第一次打开表单时(当配置文件模型中没有保存数据时),这将显示0%已完成

如果用户先前保存了3个字段,它将显示60%

我假设用户(正在填写表单)已登录

视图.py

def index(request):
    user = request.user
    if user.user_name is None:
        per = 0
    else:
        b = [user.user_name.f1, user.user_name.f2, user.user_name.f3, user.user_name.f4, user.user_name.f5]
        count = 0
        for j in b:
            if j:
                count += 1
        per = count * 20
    if request.method == 'POST':
        form = FormName(request.POST)
        if form.is_valid():
            form_save = form.save(commit=False)  # assuming you are using ModelForm.
            form_save.user = user  # user is OneToOneField
            form_save.save()
            # if you don't redirect after save, django will show same page after saving.
    else:
        form = FormName()
    context = {
        'form': form,
        'per': per
    }
    return render(request, 'templateName.html', context)

模板

<h1>{{ per }}% completed</h1>
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form  }}
    <input type="submit" value="submit">
</form>

我用这个来检查配置文件完成的百分比。如果你有不同的情况,请评论

相关问题 更多 >