0

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

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).

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 %}
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
Zoojay
  • 133
  • 10

2 Answers2

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.

yierstem
  • 1,933
  • 5
  • 21
  • 42
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.

csling
  • 326
  • 1
  • 8