Django - 如何更改forms.ModelChoiceField的值

时间:2017-02-10 10:43:53

标签: python django forms modelchoicefield

我想使用forms.ModelChoiceField从我的模型名称列输出值。我已经阅读了很多关于这个主题的文档,但证明难以达到预期的效果!

这是我的代码。

我有这样的表格:

forms.py

from django import forms
from asset_db.models import Profiles


class SubmitJob(forms.Form):

    material_id = forms.CharField(max_length=8)
    workflow = forms.ModelChoiceField(queryset=Profiles.objects.distinct('name'))
    start_datepicker = forms.CharField(max_length=12)
    end_datepicker = forms.CharField(max_length=12)

此型号:

class Profiles(models.Model):

    id = models.DecimalField(6).auto_creation_counter
    name = models.CharField(max_length=256, default='null')
    target_path = models.CharField(max_length=256, default='null')
    target_profile = models.TextField(max_length=1024, default='null')
    package_type = models.CharField(max_length=256, default='null')
    video_naming_convention = models.CharField(max_length=256, default='null')
    image_naming_convention = models.CharField(max_length=256, default='null')
    package_naming_convention = models.CharField(max_length=256, default='null')

    def __str__(self):
        return self.name

这是HTML输出:

<p><label for="id_workflow">Workflow:</label> <select id="id_workflow" name="workflow" required>
<option value="" selected="selected">---------</option>
<option value="2">Amazon</option>
<option value="1">Test</option>
</select></p>

我想知道如何更改&#34; value&#34;列#34;名称&#34;在我的模型中,例如:

<p><label for="id_workflow">Workflow:</label> <select id="id_workflow" name="workflow" required>
<option value="" selected="selected">---------</option>
<option value="Amazon">Amazon</option>
<option value="Test">Test</option>
</select></p>

提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以将to_field_name="name"添加到ModelChoiceField。这在documentation

中有解释