Reputation: 33
How to get a value from choices and display it on a form in Django? In this case (as in the picture), so that English is displayed, not en
In the template I print the form as a variable {{ form }}
. I also tried to output by one field {{ form.language.get_lang_display }}
, but in this case the language field is not displayed at all.
File models.py
class AvailableLanguage(models.Model):
LANGUAGES = (
('en', 'English'),
('ru', 'Russian'),
)
lang = models.CharField(max_length=50, unique=True, choices=LANGUAGES)
lang_code = models.CharField(max_length=5, unique=True)
slug = models.SlugField()
class Question(models.Model):
title = models.CharField(max_length=250)
language = models.ForeignKey(AvailableLanguage, on_delete=models.CASCADE, default='')
body = models.TextField()
...
File forms.py
class UserQuestion(forms.ModelForm):
class Meta:
model = Question
fields = ('title', 'language', 'body')
File add_question.html
{% block content %}
<form action="." method="post" enctype="multipart/form-data">
{# {{ form }}#}
{{ form.language.get_lang_display }} {#Not displayed#}
{% csrf_token %}
<input class="btn--primary" type="submit" value="{% trans 'Создать' %}">
</form>
{% endblock %}
Upvotes: 3
Views: 17843
Reputation: 351
use
{{ form.get_lang_display }}
instead of
{{ form.language.get_lang_display }}
Upvotes: 1
Reputation: 557
Just return a str function from your AvailableLanguage model:
class AvailableLanguage(models.Model):
LANGUAGES = (
('en', 'English'),
('ru', 'Russian'),
)
lang = models.CharField(max_length=50, unique=True, choices=LANGUAGES)
lang_code = models.CharField(max_length=5, unique=True)
slug = models.SlugField()
def __str__(self):
return self.get_lang_display()
Upvotes: 12