Django:如何访问FormHelper布局中的queryset实例

时间:2017-06-20 05:36:23

标签: django-crispy-forms

我正在使用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'),

1 个答案:

答案 0 :(得分:0)

我正在努力解决同样的问题。我实现的解决方案是创建一个字段,将其值显示为纯文本。

  1. 将plain_text表单字段添加到模型表单

  2. 实现自定义窗口小部件以将文本输入呈现为纯文本

  3. 在init

  4. 形式中设置plain_text字段值
  5. 使用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'),