2013-02-06 48 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>