Django模板获取外键值名称

时间:2017-12-19 08:55:03

标签: django

我已经制作了一个表格,其中包含有翻译问题的测试。我的问题是,我无法显示语言值名称和类型值名称,而不是显示其ID的名称。

views.py

def translator_test(request):
    tests = TranslatorTest.objects.filter(data__translator__user=request.user).filter(completed=False)
    forms = []
    for index, test in enumerate(tests):
        forms.append(TranslatorTestForm(request.POST or None, instance=test, prefix="form_{}".format(index)))
    if request.method == 'POST':
        for form in forms:
            if form.is_valid():
                cd = form.cleaned_data
                answer = cd['answer']
                test_form = form.save(commit=False)
                if answer:
                    test_form.completed = True
                else:
                    test_form.completed = False
                test_form.save()
        return redirect(reverse_lazy('core:index'))
    return render(request, 'core/translator_test.html', {'forms': forms})

translator.html

{% for form in forms %}
    {% for field in form %}
        <div class="form-group m-form__group row">
            {% if field.name == 'question' %}
                <label for="example-text-input" class="col-2 col-form-label">
                    {{ field.label }}:
                </label>
                <div style="margin-top:8px;">
                    {{ field.value }}
                </div>
            {% elif field.name == 'language' %}
                <label for="example-text-input" class="col-2 col-form-label">
                    {{ field.label }}:
                </label>
                <div style="margin-top:8px;">
                    {{ field.instance.language.name }}
                </div>
            {% elif field.name == 'type' %}
                <label for="example-text-input" class="col-2 col-form-label">
                    {{ field.label }}:
                </label>
                <div style="margin-top:8px;">
                    {{ field.value }}
                </div>
        </div>
    {% endfor %}
{% endfor %}

models.py

class Language(models.Model):
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.name

class TextType(models.Model):
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.name

class TranslatorTest(models.Model):
    language = models.ForeignKey(Language)
    type = models.ForeignKey(TextType, blank=True, null=True, default=None)

forms.py

class TranslatorTestForm(ModelForm):

    class Meta:
        model = TranslatorTest
        fields = ['question', 'answer', 'language', 'type']
        labels = {
            'question': _('Întrebare'),
            'answer': _('Răspuns'),
            'language': _('Limba'),
            'type': _('Tip'),
        }

    def __init__(self, *args, **kwargs):
        super(TranslatorTestForm, self).__init__(*args, **kwargs)
        self.fields['question'].disabled = True
        self.fields['language'].disabled = True
        self.fields['type'].disabled = True
        self.fields['answer'].widget.attrs.update({'class': 'form-control m-input', 'id': 'exampleTextarea', 'rows': 5})

当我使用{{ field.value }}时,它会显示外键值的id。 当我使用{{ field.instance.language.name }}时,它不会显示任何内容。

如何显示外键值的名称?

0 个答案:

没有答案