2010-11-04 72 views
0

我需要在django模板中放置一組div。 最簡單的方法是做是如何正確生成django模型的html

MyForm的()。as_table()

copypaste那和封裝領域的組適當的股利。唯一的問題是,當表單驗證出現錯誤時,此方法失敗,因爲{{form.fieldname.errors}}在任何地方都沒有提及。

任何更好的想法或現成的工具,會讓我無法每次手工做這件事?

這裏就是答案,如果有人需要它

def generate_object_template(object): 
    from string import Template 
    for field in object._meta.fields: 
      t = Template(""" <label>{{ form.$fieldname.label }}{% if form.$fieldname.is_required %}*{% endif %}</label> 
      {{ form.$fieldname }} 
      {% if form.$fieldname.errors %} {{ form.$fieldname.errors }}{% endif %}""").substitute(fieldname=field.attname)         
      print t 

回答

1

當你要自定義Django的形式,你可以做如下

... 
<label>{{ form.myfield.label }}{% if form.myfield.is_required %}*{% endif %}</label> 
{{ form.myfield }} 
{% if form.myfield.errors %} {{ form.myfield.errors }}{% endif %} 

<label>{{ form.myfield3.label }}{% if form.myfield3.is_required %}*{% endif %}</label> 
{{ form.myfield3 }} 
{% if form.myfield3.errors %} {{ form.myfield3.errors }}{% endif %} 

<label>{{ form.myfield2.label }}{% if form.myfield2.is_required %}*{% endif %}</label> 
{{ form.myfield2 }} 
{% if form.myfield2.errors %} {{ form.myfield2.errors }}{% endif %} 
... 

有了這樣的設置可以自定義表單在你想要的地方添加div,然後繼續進行驗證。

http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template

+0

你所寫的不允許我把DIV元素周圍3,4,5,就在所有的元素或單個元素 – damir 2010-11-04 11:38:33

+0

確定刪除{%for循環%}我犯了一個錯誤不要使用for循環只是把你的平坦的領域 – coulix 2010-11-04 12:25:28

+1

我從來沒有理解這裏的靈活性。這是我最大的(儘管仍然很小)與Django抱怨。我還創建了一個特殊的「表單循環」,其中包含變量,用於處理標題,特殊標籤等內容。 – jMyles 2010-11-04 19:25:52