How it works...

You can now use the {% like_widget for object %} template tag for any object in your website. It generates a widget that will show the Like state based on whether and how the current logged-in user has responded to the object.

The Like button has three custom HTML5 data attributes:

  • data-href supplies a unique, object-specific URL to change the current state of the widget
  • data-add-text is the translated text to be displayed when the Like association has been added (Unlike)
  • data-remove-text is similarly the translated text for when the Like association has been removed (Like)

Using django-sekizai, we add the <script src="{% static 'likes/js/widget.js' %}"></script> to the page. Note that, if there were more than one Like widget on the page, we would just include the JavaScript once. And, if there were no Like widgets on the page, then the JavaScript wasn't included on the page at all.

In the JavaScript file, Like buttons are recognized by the like-button CSS class. An event listener, attached to the document, watches for click events from any such button found in the page, and then posts an Ajax call to the URL specified by the data-href attribute.

The specified view json_set_like accepts two parameters: the content type ID and the primary key of the liked object. The view checks whether a Like exists for the specified object, and if it does, the view removes it; otherwise, the Like object is added. As a result, the view returns a JSON response with the success status, the action that was taken for the Like object (add or remove), and the total count of Likes for the object across all users. Depending on the action that is returned, JavaScript will show an appropriate state for the button.

You can debug the Ajax responses in the browser's developer tools, generally in the Network tab. If any server errors occur while you are developing, and you have DEBUG turned on in your settings, you will see the error traceback in the preview of the response; otherwise, you will see the returned JSON, as shown in the following screenshot:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.131.168