[Answered ]-Update Django Object with Jquery, possible?

2👍

It’s certainly possible and there are many ways to do this. Abstractly, all you need to do is pass the front-end some way to reference your object(s) so that jQuery (or whatever library/framework you want to use) can tell Django what object(s) needs updating. For the sake of clarity, I’ll assume you want to update a single object — but note that this same pipeline could scale to multiple objects just by using an array of identifiers/references instead of just one that we’ll be using.

One way to do this is to pass the id of the Django object into the HTML (disclaimer: there are more secure ways to do this, but for the sake of clear conceptualization it will suffice). For example, to pass the id of each of your company objects, you could use:

{% for company in companies %}
  ...
<td class="companyID">{{ company.id }}</td>
  ...
{% endfor %}

Say you wrapped each company in some wrapper, then you could just grab the id you want with a little jQuery:

var theCompany = ... // Maybe grabbed from a click? Really, it's up to you.
var theCompanyID = $(theCompany).find(".companyID").html();

Then, when you want to perform some “update” on that object, just include it in the data you send back to your view.

var data = {"theCompanyID":theCompanyID, ... }
$.post("/myURL/", data, someCallback);

After that, you can grab the corresponding Django object with MyObject.get(id=theObjectID) and update it however you need.

def myUpdateView(request):
  # We'll wrap the "update" portion in a Try-Except in case the user passes us
  # data that will break our update function. We should obviously check for
  # this BEFORE we attempt to perform the update -- but always best to be safe.
  try:
    theCompanyID = request.POST["theCompanyID"]
    theCompany = Company.objects.get(id=theCompanyID)

    # ... Now do the updates you want.

    theCompany.save()

    return HttpResponse("Update successful!")

  except:
    return HttpResponse("Oh... Update failed...")

Here’s a more in-depth tutorial if you’d like to explore this more.

Leave a comment