2013-02-06 49 views
0

我在Django中準備了一個基本聯繫表單。數據成功保存。但我想檢索保存的數據(所有數據庫列)作爲一個HTML表格,並顯示在我的網站(不在管理界面)。檢索並渲染通過Django表單提交的數據API

這裏是模型:

class ContactForm(forms.Form): 
    name = forms.CharField(label='Your name') 
    place = forms.CharField(max_length=100,label='Your place') 
    message = forms.CharField(label='Your message') 
    url = forms.URLField(label='Your Web site', required=False) 
    options = forms.BooleanField(required=False) 
    day = forms.DateField(initial=datetime.date.today) 

的觀點僅接受POST數據並重定向到一個「謝謝」頁面。

我試着做ContactForm.objects.all()但我得到的錯誤是:Objects attribute does not exist for ContactForm

+0

你可以叫objects.all()的模型,而不是形式。你可以添加模型代碼到你的問題嗎? –

回答

2

聽起來你需要創建一個model。 Django模型描述了一個數據庫表,並創建了用python處理該表的功能。如果你想保存你的數據,那麼你會希望它保存在數據庫中,並且你會想要一個模型。

嘗試類似的東西 -

from django.db import models 

class Contact(models.Model): 
    name = models.CharField(label='Your name', max_length=128) 
    place = models.CharField(max_length=100,label='Your place') 
    message = models.CharField(label='Your message', max_length=128) 
    url = models.URLField(label='Your Web site', required=False) 
    options = models.BooleanField(required=False) 
    day = models.DateField(initial=datetime.date.today) 

然後,而不是創建一個從你想從ModelForm繼承Form繼承的形式(見docs關於範本更多信息)。它應該是非常簡單的,因爲所有你字段已經在模型中描述 -

from django.forms import ModelForm 

class ContactForm(ModelForm): 
    class Meta: 
     model = Contact 

你需要將處理保存表單(here's an example from the docs)的圖。然後你就可以做Contact.objects.all()並按照Cathy的答案顯示它。或者,查看Django-Tables2 - 一個用於顯示錶格的有用插件。

0

views.py

def view_name (request): 
    contacts = Contact.objects.all() 
    return render(request, 'page.html', { 
     'contacts': contacts 
    }) 

HTML

<html> 
    .... 

    <body> 
     <table> 
     {% for contact in contacts %} 
      <tr> 
       <td>{{contact.name}}</td> 
       <td>{{contact.place}}</td> 
       <td>....</td> 
       <td>....</td> 
      </tr> 
     {% endfor %} 
     </table> 
    </body> 
</html>