Django:如何在表单中添加多个“添加另一个字段”按钮

时间:2021-07-27 21:22:02

I'm new to django and I'm having a lot of trouble with forms.

我是django的新手,我在表格方面遇到了很多麻烦。

I'm making a calculation-based tool and I need to be able to have an arbitrary number of inputs.

我正在制作一个基于计算的工具,我需要能够有任意数量的输入。

As a really basic example, let's say I want to make a calculator that will sum and subtract any number of inputs. Each number to be added or subtracted is in its own number field. Both the list of "adding" fields and the list of "subtracting" fields has its own "add another field" button.

作为一个非常基本的例子,假设我想制作一个能够求和减去任意数量输入的计算器。要添加或减去的每个数字都在其自己的数字字段中。 “添加”字段列表和“减去”字段列表都有自己的“添加另一个字段”按钮。

For starters, here's something that adds two inputs (since I can't figure out how to implement even 1 "add another field button" or understand the answer to it).

对于初学者来说,这里添加了两个输入(因为我无法弄清楚如何实现甚至1“添加另一个字段按钮”或理解答案)。

views.py

from __future__ import unicode_literals

from django.http import HttpResponse, HttpResponseRedirect

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from .forms import AddForm


def _from_str(s):
    try:
        s = int(s)
    except ValueError:
        try:
            s = float(s)
        except ValueError:
            pass
    return s


@csrf_exempt
def web_adder(request):
    if request.method == 'POST':
        form = AddForm(request.POST)
        # form = MyForm(request.POST, extra=request.POST.get('extra_field_count'))
        if form.is_valid():
            return web_adder_out(request, _from_str(form.cleaned_data['addend0']), _from_str(form.cleaned_data['addend1']))

    else:
        form = AddForm()
        # form = MyForm()
    return render(request, 'addercontent.html', {'form': form})


def web_adder_out(request, a, b):
    return render(request, 'addercontentout.html', {'content':[a + b]})

forms.py

from django import forms


class AddForm(forms.Form):
    addend0 = forms.CharField(label='first addend', max_length=100)
    addend1 = forms.CharField(label='second addend', max_length=100)

addercontent.html

{% block content %}
<p>This is a web adder</p>
<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-default">Enter</button>
</form>
{% endblock %}

addercontentout.html

{% block content %}
    {% for c in content%}
    Result: {{c}}
    <br>
    <a href="/" class="btn btn-default">Return</a>
    {% endfor %}
{% endblock %}

2 个解决方案

#1


0  

Don't use Django for the field generation. I would do all of it via HTML. Run your setup that you currently have, and you should be able to look at the page source to see how the inputs are structured. Then you can manually write the form in HTML, with JavaScript adding fields in as needed.

不要将Django用于字段生成。我会通过HTML完成所有这些工作。运行您当前拥有的设置,您应该能够查看页面源以查看输入的结构。然后,您可以在HTML中手动编写表单,并根据需要使用JavaScript添加字段。

#2


0  

Something like this? (not tested, I haven't implement add button)

像这样的东西? (未测试,我没有实现添加按钮)

forms.py

class CalcForm(forms.Form)
    first = forms.IntegerField()
    second = forms.IntegerField()

        def add(self):
            first = self.cleaned_data['first']
            second = self.cleaned_data['second']
            return first + second

views.py

def index(request):
     if request.method == "POST":
         form = CalcForm(request.POST)
         if form.is_valid():
             result = form.add()
             return render(request, 'your_result_template.html', {'result': result})
     else:
         form = CalcForm()
     return render(request, 'your_template.html', {'form': form})

your_template.html

{% block content %}
    <p>This is a web adder</p>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-default">Enter</button>
    </form>
{% endblock %}

your_result_template.html

{% block content %}
    <p>Sum:</p>
    <h2>{{ result }}</h2>
{% endblock %}

Edit: For field generation you may need javascript. I don't know why you want to use django for this kind of app.

编辑:对于字段生成,您可能需要javascript。我不知道你为什么要使用django这种应用程序。

#1


0  

Don't use Django for the field generation. I would do all of it via HTML. Run your setup that you currently have, and you should be able to look at the page source to see how the inputs are structured. Then you can manually write the form in HTML, with JavaScript adding fields in as needed.

不要将Django用于字段生成。我会通过HTML完成所有这些工作。运行您当前拥有的设置,您应该能够查看页面源以查看输入的结构。然后,您可以在HTML中手动编写表单,并根据需要使用JavaScript添加字段。

#2


0  

Something like this? (not tested, I haven't implement add button)

像这样的东西? (未测试,我没有实现添加按钮)

forms.py

class CalcForm(forms.Form)
    first = forms.IntegerField()
    second = forms.IntegerField()

        def add(self):
            first = self.cleaned_data['first']
            second = self.cleaned_data['second']
            return first + second

views.py

def index(request):
     if request.method == "POST":
         form = CalcForm(request.POST)
         if form.is_valid():
             result = form.add()
             return render(request, 'your_result_template.html', {'result': result})
     else:
         form = CalcForm()
     return render(request, 'your_template.html', {'form': form})

your_template.html

{% block content %}
    <p>This is a web adder</p>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-default">Enter</button>
    </form>
{% endblock %}

your_result_template.html

{% block content %}
    <p>Sum:</p>
    <h2>{{ result }}</h2>
{% endblock %}

Edit: For field generation you may need javascript. I don't know why you want to use django for this kind of app.

编辑:对于字段生成,您可能需要javascript。我不知道你为什么要使用django这种应用程序。