Django:如何在表单中有多个"add another field"按钮



我是 django 的新手,我在表单上遇到了很多麻烦。

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

作为一个非常基本的例子,假设我想做一个计算器,它可以对任意数量的输入求和和减去。要添加或减去的每个数字都位于其自己的数字字段中。"添加"字段列表和"减去"字段列表都有自己的"添加另一个字段"按钮。

对于初学者来说,这里有一些东西增加了两个输入(因为我甚至无法弄清楚如何实现 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)

添加内容.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 %}

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

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

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 %}

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

最新更新