简体   繁体   中英

Django - How to change value of forms.ModelChoiceField

I want to output the value from my Models Name column using forms.ModelChoiceField . I have read a lot of documentation on the subject but its proving difficult to achieve the desired results!

Here is my code.

I have this form:

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)

This model:

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

Here is the HTML output:

<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>

I want to know how to change the value of "value" to the column "name" in my model, for example:

<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>

Thanks in advance.

You can add to_field_name="name" to your ModelChoiceField. This is explained in the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM