Silvestrini
Silvestrini

Reputation: 445

Django and Ajax - Implementing an Array from Ajax to the template

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.

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

Answers (1)

Daniel Roseman
Daniel Roseman

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 throughform.cleaned_data`.

Upvotes: 1

Related Questions