Retrieving and rendering data fed via Django forms

2019-09-04 12:39发布

问题:

I have prepared a basic contact form in Django. The data gets saved successfully. But I want to retrieve the saved data (all db columns) as a html table and display it on my site (not in the admin interface).

Here is the model:

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)

The view only accepts the post data and redirects to a "thanks" page.

I tried doing ContactForm.objects.all() but the error I got was: Objects attribute does not exist for ContactForm.

回答1:

It sounds like you need to create a model. A django model describes a database table and creates the functionality to handle that table with python. If you want to save your data then you're going to want it saved in the database, and you're going to want a model for that.

Try something like -

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)

Then instead of creating a form that inherits from Form you want to inherit from ModelForm (see the docs for more info on Model Forms). It should be pretty simple because all you're fields are already described on the model -

from django.forms import ModelForm

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

You'll need a view that will handle saving the form (here's an example from the docs). Then you'll be able to do Contact.objects.all() and follow the example from Cathy's answer to display it. Alternatively, check out Django-Tables2 - a useful plugin for displaying tables.



回答2:

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>


标签: django forms