Home Ask Login Register

Developers Planet

Your answer is one click away!

Rachel Church February 2016

Create dynamic form and retreiving values on post in Django

I want the user to be able to select a time period from the drop down then select the number of appointments needed with that time span and have it added to a list. I have been able to accomplish this with simply javascript and Html, but am at a loss as how to get all the values from the table after the user clicks 'submit'.

If I used Django's form API then the fields in the table would display as editable textboxes. Is there a way to make a form with labels/non-editable text instead of fields? That way I can edit the labels with javascript and the values will get passed to the view on Post.

I am new to Django so any suggestions are welcome.


Forms.py Example - Not what I want:

class AppointmentForm(forms.Form):
TimePeriod = forms.IntegerField(label='Time Period')
Amount = forms.IntegerField(label='Amount')

AppointmentFormSet = formset_factory(AppointmentForm)


gilhad February 2016

When I solved much more complex generated form, I just created view, which collected some data, set context and rendered template.

That template was "old style" form, with all the tags written by hands/loops and so, like

{% for p in pairs %}
  <option name="name_{{p.id}}" value="{{p.val}}">
{% endfor %}


{% for v in vars %}
  <input type="text" name="{{v.name}}" value="{{v.val}}">
{% endfor %}

and the form ended in view, where I was looping over request.POST and parsing it manually (mainly)

Not very Django way, but you can do ANYTHING with this approach (and shoot yourself to any leg any time you want too)

Greg February 2016

Presumably by "labels" you just mean non-editable text, so it could be a <div> or a <p> etc - in this case you will need to have a hidden input which mirrors the content of the label, i.e.

<div class="label">Text here</div>
<input type="hidden" name="form-field-name" value="Text here">

To achieve this in your form, use a forms.HiddenInput widget:

class AppointmentForm(forms.Form):
    time_period = forms.IntegerField(widget=forms.HiddenInput)

Obviously the django form isn't going to render the way you need it to, so you'll need to render it using custom html, which will probably look something like this:

{% for field in form %}
    <div class="label">{{ field.data }}</div>
    {{ field }} 
{% endfor %}

Post Status

Asked in February 2016
Viewed 3,390 times
Voted 14
Answered 2 times


Leave an answer

Quote of the day: live life