Django forms select from choices or enter new data

Question:

I have a Django form in which for some fields I pull choices from my database, shown below.

I have another field in which the user has to manually type in the data. Is it possible to give that field choices that are present from the database and an option to enter the data if the choice isn’t there?

Example: The field name is player and I would like to have all the players already in database as options to choose from and if it is a new player, the option to enter it.

Is that what a TypedChoiceField is? I have been trying to find examples but no luck.

thanks!

    forms
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        team_names = TeamName.objects.filter(league__name='MLB').order_by('name')
        teams = [(team.id, team.name)for team in team_names]
        self.fields['team'].choices = teams
Asked By: Ryan Thomas

||

Answers:

TypedChoiceField is not what you think it is. It simply starts on a default value instead of a "——" blank value.

You could not define choices= on your model. But instead define a list of default choices outside of the model.

my_choices = (
    "foo",
    "bar",
    "pop",
)
class MyModel(models.Model):
    my_field = models.CharField(max_length=100)

Then in your view you’d want to import that tuple and pass it to you template:

from my_app.models import my_choices

def my_view(request, *a, **kw):
    # view logic
    return render(request, "path/to/my/template", choices=my_choices)

Then in your template you can have a select box with the default choices and string values. And also have an optional input type=text that will save to that field if populated.

Something like:

<select name="my_field">
<option value="" selected="selected">-----</option>
{% for choice in choices %}
    <option value="{{ choice }}">{{ choice }}</option>
{% endfor %}
</select>

Will give you default choices. Then add an input with the same name, this will act as an optional new choice.

<input type="text" name="my_field"/>

Optionally you could write javascript logic that will ensure only the selectbox or the textfield gets submitted.

Answered By: garchompstomp
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.