[Python] [Django] How to use ChoiceField and how to add options

Overview

I'm touching Choice Field in Django and I'll keep a reminder of the time-consuming parts. The sample code is here

table of contents

-[About ChoiceField](About #ChoiceField) -Sample -[Parts that took time](#Parts that took time) -[How to add choices later](#How to add choices later) -[Field's choices` property](#field's choices property) -[ChoiceField code to add choices later](#Choicefield code to add choices later)

About Choice Field

--A field to choose one from multiple choices --The default drawing is django.forms.widgets.Select --When drawn on the template, it becomes <select name =" field name "> <option value =" choice.key "> choice.value </ option> ... </ select> --Reference: Form Fields: ChoiceField

sample

from django import forms


class SampleChoiceForm(forms.Form):
    choice1 = forms.fields.ChoiceField(
        choices = (
 ('ja','Japan'),
 ('us','America'),
 ('uk','UK'),
 ('ch','China'),
 ('kr','Korea')
        ),
        required=True,
        widget=forms.widgets.Select
    )
from django.shortcuts import render
from django.views import View
from . import forms

class SampleChoiceView(View):
    def get(self, request):
        form = forms.SampleChoiceForm()
        context = {
            'form': form
        }

        return render(request, 'choice_sample.html', context)

sample_choice_view = SampleChoiceView.as_view()
<!DOCTYPE html>
<html lang="ja">
    <head>
 <title> ChoiceField sample </ title>
    </head>
    <body>
        <form method="POST" aciton="">
            {% for field in form %}
            {{ field }}
            {% endfor %}
            {% csrf_token %}
        </form>
    </body>
</html>
<!doctype html>
<html lang="ja">
<head>
<title> ChoiceField sample </ title>
</head>
<body>
 <form method="POST" action="">
   <select id="id_choice1" name="choice1">
<option value = "ja"> Japan </ option>
<option value = "us"> America </ option>
<option value = "uk"> UK </ option>
<option value = "ch"> China </ option>
<option value = "kr"> Korea </ option>
   </select>
   <input type="hidden" name="csrfmiddlewaretoken" value="xxxxxxxx" />
 </form>
</body>
</html>

display

表示結果1.png

Where it took time

--How to add options later

How to add choices later

In the official and Django Girls tutorials, fields with choices are written in the form of getting choices from the model or giving fixed choices as initial values in the ChoiceField's choice parameter. But what if you want to create this option dynamically?

Field's choices property

The Django documentation has a page called Model Field Reference (https://docs.djangoproject.com/en/2.2/ref/models/fields/) It describes the fields used in the form, including model fields. If you look for it, you will find the section Field.choices. Just in case, take a look at the ChoiceField source code.

class ChoiceField(Field):
 (Omitted)
    def _get_choices(self):
        return self._choices

    def _set_choices(self, value):
    # Setting choices also sets the choices on the widget.
    # choices can be any iterable, but we call list() on it because
    # it will be consumed more than once.
        if callable(value):
             value = CallableChoiceIterator(value)
        else:
              value = list(value)

        self._choices = self.widget.choices = value

   choices = property(_get_choices, _set_choices)
 (Omitted)

Certainly there is a property called choices. Let's use it.

ChoiceField code to add choices later

from django import forms
 (Omitted)
class SampleChoiceAddForm(forms.Form):
    choice1 = forms.fields.ChoiceField(
        required=True,
        widget=forms.widgets.Select
    )
from django.shortcuts import render
from django.views import View
from . import forms
 (Omitted)
class SampleChoiceAddView(View):
    def get(self, request):
        form = forms.SampleChoiceAddForm()
        form.fields['choice1'].choices = [
 ('11th'),
 ('2', '2nd'),
 ('3', '3rd'),
 ('4', '4th'),
 ('5', '5th'),
        ]
        context = {
            'form': form
        }

        return render(request, 'choice_sample.html', context)
 (Omitted)
sample_choice_add_view = SampleChoiceAddView.as_view()
<!DOCTYPE html>
<html lang="ja">
<head>
<title> ChoiceField sample </ title>
</head>
<body>
 <form method="POST" aciton="">
   <select name="choice1" id="id_choice1">
<option value = "1"> 1st </ option>
<option value = "2"> second </ option>
<option value = "3"> 3rd </ option>
<option value = "4"> 4th </ option>
<option value = "5"> 5th </ option>
   </select>
   <input type="hidden" name="csrfmiddlewaretoken" value="xxxxxxxx">
 </form>
</body>
</html>

display

表示結果2.png

I was able to add and go after the choices!

Recommended Posts

[Python] [Django] How to use ChoiceField and how to add options
How to install and use pandas_datareader [Python]
python: How to use locals () and globals ()
How to use Python zip and enumerate
How to use is and == in Python
[Python] How to use hash function and tuple.
python3: How to use bottle (2)
[Python] How to use list 1
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
How to use Django on Google App Engine / Python
How to use Decorator in Django and how to make it
Python: How to use async with
How to install and use Tesseract-OCR
[Python] How to use Pandas Series
How to use Requests (Python Library)
How to use SQLite in Python
How to use .bash_profile and .bashrc
How to install and use Graphviz
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to use python zip function
[Python] How to use Typetalk API
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
[Python] Summary of how to use split and join functions
Comparison of how to use higher-order functions in Python 2 and 3
[Python] Summary of how to use pandas
How to package and distribute Python scripts
[Introduction to Python] How to use class in Python?
[Python] How to add rows and columns to a table (pandas DataFrame)
[python] How to use __command__, function explanation
How to use functions in separate files Perl and Python versions
[Python] How to use import sys sys.argv
How to use Serverless Framework & Python environment variables and manage stages
[Python] Organizing how to use for statements
Memorandum on how to use gremlin python
[Python2.7] Summary of how to use unittest
How to use __slots__ in Python class
How to use "deque" for Python data
[Python] How to calculate MAE and RMSE
[Python] Understand how to use recursive functions
How to add python module to anaconda environment
Summary of how to use Python list
How to use regular expressions in Python
[Python2.7] Summary of how to use subprocess
How to add options to Django's manage.py runserver
How to use Python with Jw_cad (Part 2 Command explanation and operation)
[Blender x Python] How to use modifiers
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)