Notes on Animals AJAX

The Animals example now has AJAX star support. Here are some notes on the pieces of that.

  • The base.html file has a few additions:

    • Pull in Font Awesome CSS from CDN
    • Pull in jQuery from CDN
    • Add <script> block that sets a JavaScript variable containing the CSRF token, so we can include it in JavaScript requests.
  • The animal.html has our star widget

    • Only display if user is logged in
    • Initialize the data-state variable to checked or unchecked based on whether user has starred animal
    • Add the animal ID as an attribute data-animal-id, so that JavaScript can access the animal ID to include it in requests
    • Load JavaScript file stars.js containing the star widget logic
  • Changes to views.py

    • Add a before_request hook to set up the CSRF token in the session. This replaces that logic in index, so that we always make sure we have a CSRF token. This is a better place to put it.
    • Add logic to animal to look up whether the user starred the animal
  • New file api.py

    • Implement /api/update-star endpoint to handle star adds/removes
    • Add or delete AnimalStar objects to record whether the user has starred the animal
    • Return response as JSON object
  • New file stars.js

    • Respond to click events on the star widget by posting the appropriate request