我正在使用formset来更新成分属性列表。
IngredientFormSet = modelformset_factory(Ingredient, form=IngredientForm, extra=0)
formset = IngredientFormSet(queryset=ingredients_dictinct)
# I am passing a list of ingredients as queryset
helper = RecipeIngredientFormSetHelper()
我的表单助手代码是:
class RecipeIngredientFormSetHelper(FormHelper):
def __init__(self, *args, **kwargs):
super(RecipeIngredientFormSetHelper, self).__init__(*args, **kwargs)
self.form_method = 'post'
self.layout = Layout(
Div(
Div(HTML("{{ forloop.counter }}"),
css_class='col-xs-2', style='text-align:center'),
Div('name', css_class='col-xs-2',),
Div('munit', css_class='col-xs-2',),
Div('rate', css_class='col-xs-2',),
Div('typeofingredient', css_class='col-xs-2',),
Div('density_kg_per_lt', css_class='col-xs-2',),
Div('density_pcs_per_kg', css_class='col-xs-1',),
Div('density_pcs_per_lt', css_class='col-xs-1',),
css_class='row',style="border-top:1px solid;padding-top:20px")
)
self.add_input(Submit("submit", "Save"))
self.render_required_fields = True
在使用HTML()的self.layout中,如何显示成分对象的一些属性
如何访问布局
中查询集中传递的成分例如:
self.layout = Layout(
Div(
Div(HTML("{{ forloop.counter }}"),
HTML("{{ ingredient.somemodelmethod }}"),
css_class='col-xs-2', style='text-align:center'),
答案 0 :(得分:0)
我正在努力解决同样的问题。我实现的解决方案是创建一个字段,将其值显示为纯文本。
将plain_text表单字段添加到模型表单
实现自定义窗口小部件以将文本输入呈现为纯文本
在init
使用FormHelper中的plain_text字段而不是HTML
from django.utils.safestring import mark_safe
class PlainTextWidget(forms.Widget):
def render(self, name, value, attrs=None):
return mark_safe(value) if value is not None else '-'
class IngredientForm(forms.ModelForm):
plain_text = forms.CharField(widget=PlainTextWidget,required=False)
....
def __init__(self, *args, **kwargs):
super(IngredientForm, self).__init__(*args, **kwargs)
self.initial['plain_text'] = self.instance.somemodelmethod()
self.layout = Layout(
Div(
Div(
HTML("{{ forloop.counter }}"),
Field('plain_text'),