获取模型属性而不需要它们是modelform

编程入门 行业动态 更新时间:2024-10-28 15:32:40
获取模型属性而不需要它们是modelform_factory所必需的?(Get model attributes without making them required for modelform_factory?)

我有一个modelform_factory,它非常适合我需要的东西。

我称之为:

dep_formset = modelformset_factory( Dependent, fields=('has_medical', 'med_group_id'), max_num = dep_count )

正如您可能猜到的,Dependent有其他字段,我只想用于显示目的(分别是first_name和last_name )我想显示依赖人的first_name和last_name - 但它只是用于显示,而不是编辑。

如果我将'first_name'和'last_name'添加到上面的字段中,我可以在我的模板中访问它们 - 但是表单对.is_valid()失败了,因为我只是将它们显示为文本而不是输入,所以他们没有被POST

是否有一些聪明的方法来访问依赖对象的first_name和last_name而不将它们添加到formset_factory的字段?

模板看起来像这样(部分片段,因此您可以看到我正在尝试使用first_name,last_name):

{% for form in dep_formset %} {{ form.id }} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div class="g"> <h4>{{ form.first_name.value }} {{form.last_name.value}}</h4> </div> <div class="g dependent-option"> <div class="g-1-4 dependent-option-check"> {% if form.has_medical %}

I've got a modelform_factory which works perfect for what I need.

I call it like this:

dep_formset = modelformset_factory( Dependent, fields=('has_medical', 'med_group_id'), max_num = dep_count )

As you might guess, Dependent has additional fields that I want to use simply for display purposes (first_name and last_name respectively) I want to show the first_name and last_name of the dependent person - but have it be simply for display, not edit.

If I add 'first_name' and 'last_name' to the fields in the above, I can then access them in my template - but the form fails against .is_valid() because I'm displaying them simply as text and not as an input, so they're not being POST'ed

Is there some clever way to get access to the first_name and last_name of the dependent objects without adding them to fields for the formset_factory?

The template looks like this (partial snippet so you can see what I'm trying to do with the first_name, last_name):

{% for form in dep_formset %} {{ form.id }} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div class="g"> <h4>{{ form.first_name.value }} {{form.last_name.value}}</h4> </div> <div class="g dependent-option"> <div class="g-1-4 dependent-option-check"> {% if form.has_medical %}

最满意答案

根据提供的信息,它看起来像formset绑定到您可以在模板中访问的实例:

{{ form.instance.first_name }}

Based on provided information it looks like the formset is tied to an instance which you can access in template:

{{ form.instance.first_name }}

更多推荐

本文发布于:2023-07-30 11:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1337905.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不   属性   模型   modelform

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!