本文介绍了我如何从“第三"获取数据Django相关模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有这个模型:

class Pais(models.Model):
    nome = models.CharField('Nome', max_length=50)


class Brinq(models.Model):
    descricao = models.CharField('Nome', max_length=50)

class Filhos(models.Model):
    nome = models.CharField('Nome', max_length=50)
    idade = models.IntegerField('Idade')
    pai = models.ForeignKey('Pais')
    brinq = models.ForeignKey('Brinq', related_name='Brinq')

此视图:

def editPai(request, idpai=None):
    if idpai:
        pai = Pais.objects.get(id=idpai)
    else:
        pai = None

    ItensInlineFormSet = inlineformset_factory(Pais, Filhos, form=FilhosForm, extra=1)
    formPais = PaisForm()
    formsetItens = ItensInlineFormSet(instance=pai)

    return render_to_response("base.html", {
        "formPais": formPais,  "formsetItens": formsetItens
    }, context_instance=RequestContext(request), )

和这样的形式:

class PaisForm(ModelForm):
    class Meta:
        model = Pais

class FilhosForm(ModelForm):
    class Meta:
        model = Filhos

好,如何从模板中的"Brinq"模型获得"descricao"值?我认为这是一个简单的问题,但是,我尝试在互联网上进行查找,查找和查找,但对此一无所获.

Ok, How can I get "descricao" value from "Brinq" model in my template? I think it's a simple question but, I tried looking, looking and looking again from internet and I don't find anything about this.

我开始觉得无法使用django来做到这一点,我想相信自己是错的,但是正如我所说,我在互联网上找不到任何有关此的东西.

I start to thing it's not possible to do it using django, I want to believe that I'm wrong, but as I said, I didn't find anything about this in internet.

我尝试:

 {%  for form in formsetItens %}
  <tr>
       <td> {{ form.nome }}</td>
       <td> {{ form.idade }}</td>
       <td> {{ form.brinq__descricao }}</td>
  </tr>
  {% endfor %}

{{form.brinq.descricao}} 到,什么都没有...:(

and {{ form.brinq.descricao}} to, and nothing... :(

有人可以帮助我解决这个问题吗?

Can anyone help me with this problem?

此致

推荐答案

您正在尝试遍历FormSet.正如 docs 所说,表单集使您能够迭代表单集中的表单,并像使用常规表单一样显示它们."

You are trying to iterate over a FormSet. As the docs say "The formset gives you the ability to iterate over the forms in the formset and display them as you would with a regular form".

例如,您可以执行以下操作以显示表单中包括的所有字段:

So you can for example do the following to display all the fields included in the form:

{%  for form in formsetItens %}
    {{ form.as_table }}
{% endfor %}

..或者,如果适合您的用例,则可以将每个表单包装到一个表单标签中,然后在表单字段上循环:

..or if it fits your use case you could wrap each form into a form tag, and loop over the form fields:

{%  for form in formsetItens %}
    <form action="/contact/" method="post">
        {% for field in form %}
            <div class="fieldWrapper">
                {{ field.errors }}
                {{ field.label_tag }} {{ field }}
            </div>
        {% endfor %}
        <p><input type="submit" value="Send message" /></p>
   </form>
{% endfor %}

这篇关于我如何从“第三"获取数据Django相关模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:27