2017-06-20 44 views
1

我正在使用formset更新配料屬性列表。Django:如何訪問FormHelper佈局內的queryset實例

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 

在使用self.layout HTML(),如何顯示成分對象的某些屬性

如何訪問傳入的成分佈局內的查詢集

例如:

self.layout = Layout(
       Div(
        Div(HTML("{{ forloop.counter }}"), 
         HTML("{{ ingredient.somemodelmethod }}"), 
         css_class='col-xs-2', style='text-align:center'), 

回答

0

我解決了同樣的問題。我實現的解決方案是創建一個以純文本形式呈現其值的字段。

  1. 一個plain_text表單字段添加到模型形式

  2. 實現自定義窗口小部件呈現文本輸入爲純文本

  3. 設置窗體初始化中plain_text字段值

  4. 在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'), 
    
+0

很久以前我這樣做了。我會檢查解決方案 –