So far I have succeeded in implementing this view using dajax, but I find it very messy and as I've been reading so far it is good practice to have your view, well, in the view.py file. I've tried implementing it using this guide: http://www.micahcarrick.com/ajax-form-submission-django.html but without being able to read which button is clicked.
The same view shall still be shown after submitting (no redirection) as the page also contains plotting and other statuses of my connected instruments.
models.py
class ActiveMeas(models.Model):
channels = models.CharField(max_length=100)
technology = models.ForeignKey(TechnologyModel)
samples = models.IntegerField()
delay = models.IntegerField()
table = models.IntegerField()
stir = models.IntegerField()
forms.py
class ActiveForm(ModelForm):
class Meta:
model=ActiveMeas
html file
<form action="" method="post" id="activeform">
<div id="ajaxwrapper">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.as_p }}
<p id="sendwrapper"><input type="submit" value="Start" id="idstartbut" name="_ButtonStart"/></p>
<p id="sendwrapper"><input type="submit" value="Stop" id="idstopbut" name="_ButtonStop"/></p>
</div>
</form>
And the view file where I never get into the buttonstart or buttonstop. Another question is how do I return data to the javascript and update it from there?
views.py
def active(request):
if request.POST:
form = ActiveForm(request.POST)
if '_ButtonStart' in request.POST:
print "START"
if form.is_valid():
response_data = {'data':request.POST}
return HttpResponse(simplejson.dumps(response_data))
else:
print "NOT VALID"
response_data = {'data':request.POST}
return HttpResponse(simplejson.dumps(response_data))
elif '_ButtonStop' in request.POST:
print "STOP"
else:
form = ActiveForm()
return render(request, 'active.html', {'index': "active",'form':form})
javascript
function ActiveInit(){
$(document).ready(function () {
$(function() {
var form = $("#activeform");
form.submit(function(e) {
$("#ajaxwrapper").load(
form.attr('action') + ' #ajaxwrapper',
form.serializeArray(),
);
e.preventDefault();
});
});
}
I'm very new to both django, ajax and jQuery. So please enlighten me if something is to be done different, and how to solve my problem.