Reputation: 445
Currently I'm trying to implement Ajax with Django in order to just refresh certain sections of the web app. I'm having trouble in two parts.
None
. I'm not sure why its going in like that. I know that I managed to pass it correctly when it was directly to the views.py without going in to the Javascript file first.ajax
function in the Javascript file. What I mean is that when I do my whole instruction set in the views and return the informaation needed to ajax, I dont know what command to use to implement it in the template. Currenly I'm returning an array of chars that constantly changes order depending on the user input. At first loading, the alphabet is in order but when the user enters a number, the letters shift according to the input. I already got that part going but I'm stuck at taking it back to the template after been shifted.Also any recommendation is welcome. If you see something not right done or could be implemented in a better way, please let me know. Any code ethics is highly appreciated!
My code is here:
forms.py
class caesarCipher(forms.Form):
key = forms.DecimalField(max_value = 26, min_value = 1, initial = 1, required = True)
plaintext = forms.CharField(max_length = 8, required = True)
letter = forms.CharField(max_length = 1)
views.py
def caesarHomePage(request):
cipher = alphabet()
x = cipher.getListLetter()
y = cipher.getListLetter()
if request.method == 'POST':
form = caesarCipher(request.POST or None)
print(request.POST.get('id_key')) #THIS GIVES NONE
print(form['key'].value()) # THIS GIVES NONE
int(form['key'].value())
y = cipher.setCipherLetters(integerKey)
return HttpResponse(json.dumps({'y' : y}), content_type="application/json")
form = caesarCipher(request.POST or None)
context = { 'x': x,
'y': y,
'form': form,
}
return render(request, 'HomeCaesar.html', context)
main.js
$("#keyButtonId").on({
click : function() {
$.ajax( {
url : "http://127.0.0.1:8000/HomeCaesar/",
type : "POST",
data: { CsrfViewMiddleware: '{{ csrf_token }}', the_key: $('#id_key').val() },
success : function(json) {
// $('#id_key').val('0');
console.log(json);
$('#alteredAlphabet').append(json); // Does not work, need to change this
console.log("FUNCTION CALLED!");
}
});
}
});
Upvotes: 0
Views: 81
Reputation: 599490
The first part of your problem has nothing to do with Ajax. That is simply not how you access form data. You need to check form.is_valid(), then access the data through
form.cleaned_data`.
Upvotes: 1