如何在Django中处理多个输入表单字段

时间:2014-11-06 07:31:08

标签: python html

我想使用Django作为用户界面,在Python中注册/处理一个包含1到5个用户信息的列表。这不是典型的用户注册过程。我只是想处理用户数据。用户信息包含3个字段,名字,姓氏和性别。我能够获得一个用户信息,但不确定如何收集第二,第三,第四或第五个用户。

使用jQuery动态添加包含用户信息的输入框。它可以有1个条目或5个条目,具体取决于用户是否添加更多字段。我试图使addName.html和views.py处理列表,但它不正确。我的最终目标是使用这些数据并将其传递给我的Python程序,如我的views.py

所示
# Perform a Python Script using data gathered
# registerName = addName ('first_name', 'last_name', 'gender')

我很感谢帮助并为这篇长篇文章道歉。我想说清楚易懂。

顺便说一下,不要介意带有女性名字的男性单选按钮。这是出于示例目的。

models.py

# MySite/formtest/models.py

from django.db import models

# Create your models here.
class Form (models.Model):
    first_name = models.CharField (max_length = 20, null = False, blank = False)
    last_name = models.CharField (max_length = 20, null = False, blank = False)
    gender = models.CharField (max_length = 12, null = False, blank = False)

    def __str__(self):
        return self.first_name

addName.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form action="process" method="POST">{% csrf_token %}
        <input type="radio" name="gender" value="Male">Male
        <input type="radio" name="gender" value="Female">Female

        <p><label for="firstName">First Name: </label>
        <input id="firstName" type="text" name="firstName1" placeholder="John" required="True" maxlength="20">
        <label for="lastName">Last Name: </label>
        <input id="lastName" type="text" name="lastName1" placeholder="Doe" required="True" maxlength="20">
        <input type="button" value="add"></p>

        <p><label for="firstName">First Name: </label>
        <input id="firstName" type="text" name="firstName2" placeholder="John" required="True" maxlength="20">
        <label for="lastName">Last Name: </label>
        <input id="lastName" type="text" name="lastName2" placeholder="Doe" required="True" maxlength="20">
        <a href="#">remove</a></p>
        <p><input type="submit" value="Process Name"></p>
    </form>
</body>
</html>

views.py

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from formtest.models import Form

# Create your views here.
def addNameDisplay (request):
    c = {}
    c.update (csrf (request))
    return render (request, 'formtest/addName.html')

def Process (request):
    i = 1

    while (i <= 5):
        Form (first_name = request.POST ['firstName[i]'],
              last_name = request.POST ['lastName[i]'],
              gender = request.POST ['gender']).save ()

        # Perform a Python Script using data gathered
        # registerName = addName ('first_name', 'last_name', 'gender')
        i += 1

    return HttpResponseRedirect ('results')

def Results (request):
    nameInfo = Form.objects.all ()
    context = {'nameInfo': nameInfo}
    return render (request, 'formtest/results.html', context)

results.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>User Information</title>
</head>
<body>
    {% for name in nameInfo %}
    <li><b>First Name</b>: {{ name.first_name }} <b>Last Name</b>: {{ name.last_name }} <b>Gender</b>: {{ name.gender }}</li>
    {% endfor %}

    <a href="addname">Add More Names</a>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

根据HTML标准规则,ID属性必须是唯一的,因此您不能有多个id = firstName,这意味着您的ID应该增加您的名称ATTR的INSTEAD。你的名字应该是相同的,例如所有名字字段NAME都应该是firstName。

这将创建一个名为firstName的POST数组,其中每个ID都是子项。此名称/ ID行为/关系对于复选框/单选按钮是正常的,但也适用于大多数/任何表单元素。

您可以在POST中循环遍历每个名​​称(ed)attr,而不是使用while循环。 e.g。

for firstname in request.POST['firstName']:

此外,在您的视图中,您可以检查以确保可以在Django Forms文档中查看form.is_valid()。

例如:

def my_view(request):
    form = MyForm(request.POST or None)
    if form.is_valid():
        try:
            for blah in blah:
                #this is where you would obtain FN, LN and GN for EACH "user" and put it into kwargs
                kwargs = {}
                form.save(**kwargs)
        except:
            #you are responsible for determining what to do on failure
    context = {'form': form}
    return render(request, 'register.html', context)