【问题标题】:How to access infromation from parent model Django HTML Tags如何从父模型 Django HTML 标签中访问信息
【发布时间】:2020-06-30 08:26:13
【问题描述】:

我在一个名为 ContactIndex 的视图中呈现了两个表单集,该视图的父模型是 CustomUser 模型。我想在我的 html 模板中显示用户对象的 first_name。我试过这些标签没有成功有什么建议吗?

这是我的 HTML 模板中的标签:

{{ customuser.first_name }} - 不起作用

{{ object.first_name }} - 不起作用

这是我的看法:

def ContactIndex(request, CustomUser_id):
        customuser = CustomUser.objects.get(pk=CustomUser_id)
        if request.method == "POST":
            ContactFormset = ContactInlineFormSet(request.POST, request.FILES, instance=customuser)
            AddressFormset = AddressInlineFormSet(request.POST, request.FILES, instance=customuser)
            if ContactFormset.is_valid() or AddressFormset.is_valid():
                AddressFormset.save()
                ContactFormset.save()
                # Do something. Should generally end with a redirect. For example:
                return redirect ('ContactIndex', CustomUser_id=customuser.id)
        else:
            ContactFormset = ContactInlineFormSet(instance=customuser)
            AddressFormset = AddressInlineFormSet(instance=customuser)
        return render(request, 'members/member_contact_form.html', {'ContactFormset':ContactFormset, 'Address

Formset':AddressFormset })

【问题讨论】:

    标签: django django-models django-forms django-views django-templates


    【解决方案1】:

    您可以通过以下方式访问它

    {% for form in ContactFormset %}
        {{ form.instance.MODEL_FIELD_NAME }}
    {% endform %}
    

    如果你需要在表单循环之外获取实例,你最好提供额外的上下文

    return render(request, 'members/member_contact_form.html', {
        'ContactFormset':ContactFormset, 
        'AddressFormset':AddressFormset,
        'customuser': customuser,
    })
    

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 2011-01-10
      • 2020-11-16
      • 2020-08-11
      • 2021-04-12
      • 2011-05-15
      相关资源
      最近更新 更多