Django and AJAX

Hello everyone, I have learned a lot for the last week on using Django. Now a little bit more different problem which I am not sure how to solve.
I have a model which has BoolenField. When an instance of this model is displayed on the home page I want it to have like a button that changes the boolean value Asynchronous( obviously checks if is a false change to true and opposite).
I have no experience with AJAX and I am not sure if this is the right way to tackle the problem.

Many thanks in advance!

I’m not clear on what you’re trying to accomplish.

  • You’re displaying an instance of a model on a page.
  • This model contains a boolean field.
    (How is this boolean field being displayed on the page?)
  • You also want a button on that same page.
  • Pressing the button causes the boolean field to both be changed on the page and on the model.

Am I close?

Yes, so I have and if-else statement in the template which checks if the boolean is true and displays a button with a text - “Remove from favorite” if false - button with text “Add to favorite”.
Since this is just a prototype a model object being true/false for all users should be fine - I do not need ManyToMany relationship for this instance.

Then the simplest solution doesn’t involve AJAX. You can have the button linked to a URL, which takes the primary key of the model as a parameter. In the view, you switch the value of the boolean and re-render the page.

Once you’ve got that working, then you can extend it to be done without a full page refresh. But that will involve some JavaScript within the page. Are you currently using a JavaScript library such as jQuery, or a more full-featured framework (like Vue)?

If not, you can still do it with plain JavaScript, but I think you’d find it a lot easier using jQuery.

Either way, your view would remain almost the same, the difference would probably be that instead of rendering and returning a full page, you would return a json object that your JavaScript would use to update the page.

I do not want to refresh the page, It should be similar to the like buttons in Facebook. There are some tutorials about implementing a like button that I tried, but unfortunately they are pretty old and some features doesn’t work as it supposed to with the newest Django version.

I am using plain JavaScript at the moment, since I don’t have much experience with JS libraries yet.

Right now I am stuck on the view. I want to retrieve the model from the db and check its value.
To do that do I need to assign to each button (that will act as a AJAX request) the pk of the model object and on click pass the pk to the view, so the view can extract the model from the DB, check its value and change it?

Yes, that’s one way to do it

Thanks again for your help!