Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 288
death and gravity Avatar asked Jan 04 '23 13:01

death and gravity


1 Answers

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

like image 57
voodoo-burger Avatar answered Jan 07 '23 02:01

voodoo-burger