[Fixed]-How to retain data type in django form submitted through AJAX

1👍

When you send data to the server, the server will always receive/process it as a String. Unless you are using a Django Form to handle the data. In this case, Django will do the magic and convert everything to the proper type.

If you are sending the data using AJAX, you could perhaps just use $('#add_member_Form').serialize() instead of $('#add_member_Form').serializeArray(), like this:

$.ajax({
  url: 'members/new/',
  type: 'post',
  data: $('#add_member_Form').serialize(),
  success: function (data) {
    // do whatever with the data
  }
});

And now considering you have the following input in the HTML:

  • first_name
  • last_name
  • gender

You will be able to retrieve this data like this:

def add_member(request):
    first_name = request.POST.get('first_name')
    last_name = request.POST.get('last_name')
    try:
        gender = int(request.POST.get('gender'))  # try to convert the string to int
    except ValueError:  # the post data was not a valid integer
        gender = 1  # fallback to a default value? the ideal case would run a validation using a proper Form

    member = Member.objects.create(first_name=first_name, last_name=last_name, gender=gender)
    return redirect('members_list')

But you can take a step further and use a Django Form, like this:

from django import forms
from .models import Member

class MemberForm(forms.ModelForm):
    class Meta:
        model = Member
        fields = ('first_name', 'last_name', 'gender', )

And then in the view, you could simply do something like this:

def add_member(request):
    if request.method == 'POST':
        form = MemberForm(request.POST)  # here Django will process your form, convert all the data types
        if form.is_valid():  # Then you can save the data that came from the Ajax request, or do whatever
            form.save()
            return redirect('members_list')
    else:
        form = MemberForm()
    return render(request, 'add_member.html', {'form': form})

Leave a comment