首页 > 解决方案 > 如何提取 django 表单字段?

问题描述

我在forms.py中有以下脚本

from django import forms
from .models import UserLog
from crispy_forms.helper import FormHelper

PC_CHOICES = (
        ("1", "lab0034"),
        ("2", "lab0127"),
        ("3", "lab0128"),
    )

class UserLogForm(forms.ModelForm):
    class Meta:
        model = UserLog
        fields = [
            'data_location',
            'pc',
            'scenario',
            'description',
        ]
    data_location = forms.CharField(max_length=1000, widget=forms.TextInput)
    pc = forms.ChoiceField(choices=PC_CHOICES)
    scenario = forms.CharField(max_length=20)
    description = forms.CharField(widget=forms.Textarea)

我想在 HTML 页面(JS 代码)中使用表单字段。我在 html 页面中有以下代码

<script type="text/javascript">
        var data_location = ' {{ form.data_location }} '
        var pc_index = ' {{ form.pc }} '
        console.log(pc_index);
</script>

我可以在这里获得电脑的索引。但是如何获得 pc 的价值呢?例如,如果索引为 1,则应显示 pc lab0127?。

标签: django

解决方案


尝试这个

{{ form.get_pc_display }}

推荐阅读