python - Django: How to have multiple "add another field" buttons in a form -
i'm new django , i'm having lot of trouble forms.
i'm making calculation-based tool , need able have arbitrary number of inputs.
as basic example, let's want make calculator sum , subtract number of inputs. each number added or subtracted in own number field. both list of "adding" fields , list of "subtracting" fields has own "add field" button.
for starters, here's adds 2 inputs (since can't figure out how implement 1 "add field button" or understand answer it).
views.py
from __future__ import unicode_literals django.http import httpresponse, httpresponseredirect django.shortcuts import render django.views.decorators.csrf import csrf_exempt .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 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 %} {% c in content%} result: {{c}} <br> <a href="/" class="btn btn-default">return</a> {% endfor %} {% endblock %}
don't use django field generation. of via html. run setup have, , should able @ page source see how inputs structured. can manually write form in html, javascript adding fields in needed.
Comments
Post a Comment