检索和呈现通过Django表单API提供的数据

时间:2013-02-06 07:23:21

标签: django forms

我在Django准备了一个基本的联系表格。数据成功保存。但是我希望将保存的数据(所有数据库列)检索为html表并将其显示在我的站点上(而不是在管理界面中)。

以下是模型:

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)

视图只接受发布数据并重定向到“感谢”页面。

我尝试过ContactForm.objects.all(),但我收到的错误是:Objects attribute does not exist for ContactForm

2 个答案:

答案 0 :(得分: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)

然后,不要创建一个继承自Form的表单,而是要继承ModelForm(有关模型表单的更多信息,请参阅docs)。它应该非常简单,因为您已经在模型中描述了所有字段 -

from django.forms import ModelForm

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

您需要一个能够处理保存表单的视图(here's an example from the docs)。然后你就可以Contact.objects.all()并按照凯茜的回答中的例子来展示它。或者,查看Django-Tables2 - 一个用于显示表格的有用插件。

答案 1 :(得分: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>