I want a model with 5 choices, but I cannot enforce them and display the display value in template. I am using CharField(choice=..) instead of ChoiceField or TypeChoiceField as in the docs. I tried the solutions here but they don't work for me (see below).
model.py:
class Language(models.Model):
language = models.CharField(max_length=20,blank=False)
ILR_scale = (
(5, 'Native'),
(4, 'Full professional proficiency'),
(3, 'Professional working proficiency'),
(2, 'Limited professional proficiency'),
(1, 'Elementary professional proficiency')
)
level = models.CharField(help_text='Choice between 1 and 5', default=5, max_length=25, choices=ILR_scale)
def level_verbose(self):
return dict(Language.ILR_scale)[self.level]
class Meta:
ordering = ['level','id']
def __unicode__(self):
return ''.join([self.language, '-', self.level])
view.py
..
def index(request):
language = Language.objects.all()
..
mytemplate.html
<div class="subheading strong-underlined mb-3 my-3">
Languages
</div>
{% regroup language|dictsortreversed:"level" by level as level_list %}
<ul>
{% for lan_list in level_list %}
<li>
{% for lan in lan_list.list %}
<strong>{{ lan.language }}</strong>: {{ lan.level_verbose }}{%if not forloop.last%},{%endif%}
{% endfor %}
</li>
{% endfor %}
</ul>
From shell:
python3 manage.py shell
from resume.models import Language
l1=Language.objects.create(language='English',level=4)
l1.save()
l1.get_level_display() #This is good
Out[20]: 'Full professional proficiency'
As soon as I create a Language instance from shell I cannot load the site. It fails at line 0 of the template with Exception Type: KeyError, Exception Value: '4', Exception Location: /models.py in level_verbose, line 175 (which is the return line of the level_verbose method).
Also, I was expecting a validation error here from shell:
l1.level='asdasd'
l1.save() #Why can I save this instance with this level?
And I can also save a shown above when using ChoiceField, meaning that I do not understand what that field is used for.
How to force instances to take field values within choices, and display the display value in templates?