I had a index page where the user could select a few things on a form (not backed by a model) and then hopefully send off those parameters to the next form. I read that passing post data from one form to the next isn't ideal (So my design is probably not) though i just was trying to accomplish a quick proof of concept.
Since it wasn't ideal, I thought AJAX on the index form that could come back with the results of the selected params from that form would be the key. I haven't done much Ajax especially in django and so I used this website here to get some bearings:
How to submit form without refreshing page using Django, Ajax, jQuery?
I got the code I thought implemented correctly... yet when I click submit on the form it it shows me a page with just a json string on it.
views.py:
def change_detection_index(request):
#this is a good attempt at an ajax call...
if request.method == 'POST':
form = ChangeDetectForm(request.POST)
message = 'something wrong!'
if form.is_valid():
points = form.cleaned_data.get('points')
delta = form.cleaned_data.get('delta')
#frefresh the list with this info... ajax way.
message = str(points) + " " + str(delta)
# do something with your results
return HttpResponse(json.dumps({'message': message}))
else:
form = ChangeDetectForm
return render_to_response('swsite/changedetection/index.html', {'form':form },
context_instance=RequestContext(request))
index.html template
{% extends "swsite/base2.html" %}
{% load staticfiles %}
<script src= "{% static 'swsite/js/changedetection_index.js' %}" ></script>
{% block title %}NGA Research-SW: Projects{% endblock %}
{% block content %}
<section class="wrapper style4 container">
<!-- Content -->
<div class="content">
<section>
<div class="message"></div>
<div>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit Feedback" />
</form>
</div>
</section>
</div>
</section>
{% endblock %}
forms.py
class ChangeDetectForm(forms.Form):
delta = forms.CharField(max_length=20)
objectlist = ChangeDetectCSV.objects.all()
#multiple select option here taken from the damn code
points = ModelChoiceField(queryset=ChangeDetectCSV.objects.all(), empty_label = "Select points")
javascript:
$('#form').submit(function(e){
$.post('/url/', $(this).serialize(), function(data){ ...
$('.message').html(data.message);
alert(data.message);
// of course you can do something more fancy with your respone
});
e.preventDefault();
});
Maybe I used this too verbatim. But I am curious what causes the submit to display this:
It is almost like the js isn't getting called (I see no alert pop up) but I also see no console errors in the web developer console.