在Django中显示POST数据

时间:2014-12-11 00:15:15

标签: django

我不确定在success.html页面上显示POST数据的位置或方法。目前,它只显示formset的最后一个条目。我知道它需要在html文件中使用for循环,但不知道如何在捕获的数据上传递或循环它。

views.py

from django.shortcuts import render
from django.forms.formsets import formset_factory
from nameform.forms import NameForm
from nameform.addName import webform


# Create your views here.
def addname (request):
    NameFormSet = formset_factory (NameForm, extra = 2, max_num = 3)    # Set maximum to avoid default of 1000 forms.
    if request.method == 'POST':
        formset = NameFormSet (request.POST)

        if formset.is_valid ():
            location = request.POST ['site']
            data = formset.cleaned_data

            for form in data:
                firstname = form ['first_name']
                lastname = form ['last_name']

                context = {'first_name': firstname, 'last_name': lastname, 'location': location}

                webform (firstname, lastname, location)

            return render (request, 'nameform/success.html', context)

    else:
        formset = NameFormSet ()

    return render (request, 'nameform/addname.html', {'formset': formset})


success.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Successfully Added</title>
</head>
<body>
    <h1>Information captured:</h1>
    <p>{{ first_name }} {{ last_name }} {{ location }}</p>
    <a href="{% url 'addname' %}">Add more names</a>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

有很多方法可以去。这是一个例子

# ...
if formset.is_valid ():
    location = request.POST ['site']
    data = formset.cleaned_data

    names = {
        'first_names': [],
        'last_names' : []
    }

    for form in data:
        names['first_names'].append(form['first_name'])
        names['last_names'].append(form['last_name'])

    context = {'names': names, 'location': location}
    # ...

并在您的模板中

{% for key,value in names.items %}
    <b>{% cycle 'First name' 'Last name' %}</b><br>
    <span>{{ value }}</span>
{% endfor %}

答案 1 :(得分:-1)

我做了以下更改,似乎有效。

views.py

context = {'data': data, 'location': location}
...
return render (request, 'nameform/success.html', context)


success.html

{% for name in data %}
<p>{{ name.first_name }} {{ name.last_name }} {{ location }}
{% endfor %}