Giter Club home page Giter Club logo

pinax-likes's Introduction

Pinax Likes

CircleCi Codecov

Table of Contents

About Pinax

Pinax is an open-source platform built on the Django Web Framework. It is an ecosystem of reusable Django apps, themes, and starter project templates. This collection can be found at http://pinaxproject.com.

Where you can find what you need:

pinax-likes

pinax-likes is a liking app for Django, allowing users to "like" and "unlike" any model instance in your project. Template tags provide the ability to see who liked an object, what objects a user liked, and more.

pinax-likes is not a karma system. It does not have down-voting.

Overview

Supported Django and Python Versions

Django / Python 3.6 3.7 3.8
2.2 * * *
3.0 * * *

Documentation

Installation

To install pinax-likes:

    $ pip install pinax-likes

Add pinax.likes to your INSTALLED_APPS setting:

    INSTALLED_APPS = [
        # other apps
        "pinax.likes",
    ]

Add the models that you want to be likable to PINAX_LIKES_LIKABLE_MODELS in your settings file:

    PINAX_LIKES_LIKABLE_MODELS = {
        "app.Model": {}  # override default config settings for each model in this dict
    }

Add pinax.likes.auth_backends.CanLikeBackend to your AUTHENTICATION_BACKENDS (or use your own custom version checking against the pinax.likes.can_like permission):

    AUTHENTICATION_BACKENDS = [
        # other backends
        "pinax.likes.auth_backends.CanLikeBackend",
    ]

Add pinax.likes.urls to your project urlpatterns:

    urlpatterns = [
        # other urls
        url(r"^likes/", include("pinax.likes.urls", namespace="pinax_likes")),
    ]

Usage

Add each model that you want to be likable to the PINAX_LIKES_LIKABLE_MODELS setting:

    PINAX_LIKES_LIKABLE_MODELS = {
        "profiles.Profile": {},
        "videos.Video": {},
        "biblion.Post": {},
    }

Display "like" widgets in your Django templates. Suppose you have a detail page for a blog post. First load the template tags:

    {% load pinax_likes_tags %}

In the body where you want the liking widget to go, add:

    {% likes_widget request.user post %}

Finally, ensure you have eldarion-ajax installed:

Eldarion AJAX

The likes_widget templatetag above and the "toggle like" view both conform to an AJAX response that eldarion-ajax understands. Furthermore, the templates that ship with this project will work seemlessly with eldarion-ajax. Include the eldarion-ajax.min.js Javascript package in your base template:

    {% load staticfiles %}
    <script src="{% static "js/eldarion-ajax.min.js" %}"></script>

and include eldarion-ajax in your site JavaScript:

    require('eldarion-ajax');

Using Eldarion AJAX is optional. You can roll your own JavaScript handling as the view also returns data in addition to rendered HTML. Furthermore, if you don't want ajax at all the view will handle a regular POST and perform a redirect.

Signals

Both of these signals are sent from the Like model in the view that processes the toggling of likes and unlikes.

pinax.likes.signals.object_liked

This signal is sent immediately after the object is liked and provides the single kwarg of like which is the created Like instance.

pinax.likes.signals.object_unliked

This signal is sent immediately after the object is unliked and provides the single kwarg of object which is the object that was just unliked.

Filters

likes_count

Returns the number of likes for a given object:

    {{ obj|likes_count }}

Template Tags

who_likes

An assignment tag that fetches a list of likes for a given object:

    {% who_likes car as car_likes %}

    {% for like in car_likes %}
        <div class="like">{{ like.sender.get_full_name }} likes {{ car }}</div>
    {% endfor %}

likes

The likes tag will fetch into a context variable a list of objects that the given user likes. This tag has two forms:

  1. Obtain likes of every model listed in settings.PINAX_LIKES_LIKABLE_MODELS:
    {% likes user as objs %}
  1. Obtain likes for specific models:
    {% likes user "app.Model" as objs %}
Example:
    {% likes request.user "app.Model" as objs %}
    {% for obj in objs %}
        <div>{{ obj }}</div>
    {% endfor %}

render_like

This renders a like. It combines well with the likes templatetag for showing a list of likes:

    {% likes user as like_list %}
    <ul>
        {% for like in like_list %}
            <li>{% render_like like %}</li>
        {% endfor %}
    </ul>

The render_like tag looks in the following places for the template to render. Any of them can be overwritten as needed, allowing you to customize the rendering of the like on a per model and per application basis:

  • pinax/likes/app_name/model.html
  • pinax/likes/app_name/like.html
  • pinax/likes/_like.html

likes_widget

This renders a fragment of HTML the user clicks on to unlike or like objects. It only has two required parameters, the user and the object:

    {% likes_widget user object %}

It renders pinax/likes/_widget.html. A second form for this templatetag specifies the template to be rendered:

    {% likes_widget request.user post "pinax/likes/_widget_brief.html" %}

liked

This template tag decorates an iterable of objects with a liked boolean indicating whether or not the specified user likes each object in the iterable:

    {% liked objects by request.user as varname %}
    {% for obj in varname %
        <div>{% if obj.liked %}* {% endif %}{{ obj.title }}</div>
    {% endfor %}

Settings

PINAX_LIKES_LIKABLE_MODELS

A dictionary keyed by "<appname.model>". Each model value is a dictionary containing context keys and values.

Context value keys are CSS element names used in template rendering for each model:

"count_text_singular"
"count_text_plural"
"css_class_off"
"css_class_on"
"like_text_off"
"like_text_on"

Here is an example from the test settings used on this project found in runtests.py.

    PINAX_LIKES_LIKABLE_MODELS = {
        "auth.User": {
            "like_text_on": "unlike",
            "css_class_on": "fa-heart",
            "like_text_off": "like",
            "css_class_off": "fa-heart-o",
            "allowed": lambda user, obj: True
        },
        "tests.Demo": {
            "like_text_on": "unlike",
            "css_class_on": "fa-heart",
            "like_text_off": "like",
            "css_class_off": "fa-heart-o"
        }
    },

Templates

pinax-likes uses minimal template snippets rendered with template tags.

Default templates are provided by the pinax-templates app in the likes section of that project.

Reference pinax-templates installation instructions to include these templates in your project.

View live pinax-templates examples and source at Pinax Templates!

Customizing Templates

Override the default pinax-templates templates by copying them into your project subdirectory pinax/likes/ on the template path and modifying as needed.

For example if your project doesn't use Bootstrap, copy the desired templates then remove Bootstrap and Font Awesome class names from your copies. Remove class references like class="btn btn-success" and class="icon icon-pencil" as well as bootstrap from the {% load i18n bootstrap %} statement. Since bootstrap template tags and filters are no longer loaded, you'll also need to update {{ form|bootstrap }} to {{ form }} since the "bootstrap" filter is no longer available.

_like.html

_widget.html

_widget_brief.html

Change Log

4.0.0

  • Drop Django 1.11, 2.0, and 2.1, and Python 2,7, 3.4, and 3.5 support
  • Add Django 2.2 and 3.0, and Python 3.6, 3.7, and 3.8 support
  • Update packaging configs
  • Direct users to community resources

3.0.3

  • Change receiver_object_id type to BigIntegerField

3.0.2

  • Add makemigrations.py file

3.0.1

  • Add django>=1.11 to requirements
  • Improve documentation markup
  • Remove doc build support
  • Update CI config
  • Replace pinax-theme-bootstrap with pinax-templates for testing

3.0.0

  • Drop Django 1.8 and 1.10 support
  • Improve documentation

2.2.1

  • Correct LONG_DESCRIPTION app title

2.2.0

  • Add Django 2.0 compatibility testing
  • Drop Django 1.9 and Python 3.3 support
  • Move documentation into README
  • Convert CI and coverage to CircleCi and CodeCov
  • Add PyPi-compatible long description

2.1.0

  • adds context and request to the likes_widget template tag

2.0.4

  • Improve documentation

2.0.1

  • Converted documentation to Markdown format

2.0.0

  • Converted to Django class-based generic views.
  • Added URL namespace."pinax_likes"
  • Added tests.
  • Dropped support for Django 1.7
  • Added compat.py in order to remove django-user-accounts dependency.

1.2

  • like_text_off and css_class_off are passed into widget even if can_like is False.
  • PINAX_LIKES_LIKABLE_MODELS entries now take an optional extra value allowed whose value should be a callable taking user and obj and returning True or False depending on whether the user is allowed to like that particular object

1.1.1

  • Fixed regression causing error when widget displayed while unauth'd

1.1

  • Fixed urls.py deprecation warnings
  • Fixed unicode string
  • Added support for custom User models
  • Documentation updates

1.0

  • Added an admin.py

0.6

  • Added a likes\_widget\_brief to display a brief widget template (likes/\_widget\_brief.html)

0.5

  • Added a who\_likes template tag that returns a list of Like objects for given object

0.4.1

  • Made the link in the default widget template a bootstrap button

0.4

  • Fixed isinstance check to check models.Model instead of models.base.ModelBase
  • Added permission checking
  • Added rendering of HTML in the ajax response to liking
  • Got rid of all the js/css cruft; up to site owner now but ships with bootstrap/bootstrap-ajax enabled templates
  • Updated use of datetime.datetime.now to timezone.now

Backward Incompatibilities

  • Added an auth\_backend to check permissions, you can just add the likes.auth\_backends.PermCheckBackend and do nothing else, or you can implement your own backend checking the likes.can\_like permission against the object and user according to your own business logic.
  • No more likes_css, likes_js, or likes_widget_js tags.
  • PINAX_LIKES_LIKABLE_MODELS has changed from a list to a dict
  • likes_widget optional parameters have been removed and instead put into per model settings

0.3

  • Renamed likes\_css and likes\_widget to likes\_css and likes\_widget
  • Turned the JavaScript code in to a jQuery plugin, removed most of the initialization code from the individual widget templates to a external JavaScript file, and added a {% likes\_js %} tag to load this plugin.
  • Each like button gets a unique ID, so multiple like buttons can appear on a single page
  • The like form works without JavaScript.
  • Likable models need to be added to PINAX\_LIKES\_LIKABLE\_MODELS setting. This prevents users from liking anything and everything, which could potentially lead to security problems (eg. liking entries in permission tables, and thus seeing their content; liking administrative users and thus getting their username).
  • Added request objects to both object\_liked and object\_unliked signals.

Backward Incompatibilities

  • Pretty much all the template tags have been renamed and work slightly differently

0.2

  • Made it easier to get rolling with a like widget using default markup and JavaScript
  • Added returning the like counts for an object when it is liked or unliked so that the widget (either your own or using the one that ships with likes) can update via AJAX

Backward Incompatibilities

  • Removed likes\_ajax and likes\_form template tags so if you were using them and had written custom overrides in \_ajax.js and \_form.html you'll need to plan your upgrade accordingly.
  • Changed the url pattern, likes\_like\_toggle, for likes to not require the user pk, instead, the view handling the POST to this url, uses request.user.
  • Changed the ajax returned by the like\_toggle view so that it now just returns a single element: {"likes\_count": \<some-number\>}

0.1

  • Initial release

Contribute

Contributing information can be found in the Pinax community health file repo.

Code of Conduct

In order to foster a kind, inclusive, and harassment-free community, the Pinax Project has a Code of Conduct. We ask you to treat everyone as a smart human programmer that shares an interest in Python, Django, and Pinax with you.

Connect with Pinax

For updates and news regarding the Pinax Project, please follow us on Twitter @pinaxproject and check out our Pinax Project blog.

License

Copyright (c) 2012-present James Tauber and contributors under the MIT license.

pinax-likes's People

Contributors

arthur-wsw avatar askeyt avatar brosner avatar dheeru0198 avatar grahamu avatar hramezani avatar jacobwegner avatar jeffbowen avatar joshkersey avatar jtauber avatar katherinemichel avatar mfonism avatar paltman avatar rizumu avatar shabda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pinax-likes's Issues

HTTP ERROR 405

Django 2.2.1

The steps are as follows:

  • pip3 install pinax-likes

  • Added 'pinax.likes', to the project's settings.py file,
    then added:

PINAX_LIKES_LIKABLE_MODELS = {
    "app.Post": {}
}
  • Added
re_path(r'^likes/', include(('pinax.likes.urls', 'pinax_likes'), namespace='pinax_likes')),

to the project's urls.py file,

  • Download the files in the https://github.com/pinax/pinax-templates/tree/master/pinax/templates/templates/pinax/likes,

put these html files in /home/www/venv/templates/pinax/likes/,

  • Added
{% load pinax_likes_tags %}
{% likes_widget request.user post %}

to the post.html file,

The console displays the following information:

Method Not Allowed (GET): /likes/like/14:13/
Method Not Allowed: /likes/like/14:13/
[29/May/2019 10:00:00] "GET /likes/like/14:13/ HTTP/1.1" 405 0

  • Then i added <script src="{% static 'eldarion-ajax.min.js' %}"></script> in base.html,

After clicked the icon, the console displays the following information:

Forbidden (CSRF token missing or incorrect.): /likes/like/14:13/
[29/May/2019 10:01:31] "POST /likes/like/14:13/ HTTP/1.1" 403 2513

What are the steps wrong? Thank you!

help with errors

i get this errors when i liked :
Method not allowed (get): /likes/like/7:2/

And this one:
Forbidden (CSRF token missing or icorret.)
Post 403

I have all settings like cloudspotting2
And have eldarion-ajax.min.js v0.17.0

Dislikes? Pinax-karma

I want a like system where users can like or dislike or choose not to do both.

Can you guys give a clue on where to edit and what to change so that I can implement this?

I want dislikes cos I'm trying to build a reddit clone with Pinax.

I hope this will be implemented if it already isn't.

Maybe there is a need for the reusable app Pinax-karma.

correct and normalize documentation

The documentation refers to likes when it should be pinax.likes. Similar mismatches occur throughout. Improve the index page. Convert pages to .MD format.

create new release

The latest changes are not reflected in the current version served up by PyPi, "1.3.1". Let's get the current code version updated and released for inclusion in demo starter projects.

ajax post failing with 403

Not sure this is the ultimate solution, but the ajax call made by the a.click is failing with a 403. The solution (workaround?) is to add a csrf_exempt decorator around the views.like_toggle() function
@login_required
@require_POST
@csrf_exempt
def like_toggle(request, content_type_id, object_id):

i believe this is something required for django 1.2 and above

Fix auth backend to respect LIKABLE_MODELS setting

When switching to using has_perm and an auth backend for permissions, the filtering through LIKABLE_MODELS went away which reopens exposure to the vulnerable that that filtering addressed. Put this back into place in the auth backend.

Use CBV

I think current view will be replace with CBV.

What do you think is better for handling ajax in CBV ?

  • Hardcode in app a way to handle ajax response
  • Use braces and his AjaxResponseMixin, JSONResponseMixin or another django ajax app
  • Create an app pinax-ajax we contain mixins such as braces has and can be used in all other pinax apps that need ajax

minor doc errors

on this page http://phileo.readthedocs.org/en/latest/templatetags.html
refers to phileo_widget as {% likes_widget user object %}

also, you don't mention the change in naming for the auth backend. in changelog 0.4 it has
"phileo.auth_backends.PermCheckBackend" but 0.5 uses "phileo.auth_backends.CanLikeBackend"

you could also save folks some time by mentioning the use of bootstrap-ajax.js in the installation section

thanks for an excellent app!

receiver_object_id size

If I have a model that has an id of type BigIntegerField, I will get an error since the size of receiver_object_id in the Like model is only a PositiveIntegerField. Is the only way of fixing this to change the Like model to use BigIntegerField?

FA icons not showing up (Django3.1)

I couldn't get the FA icons to show up until I included:

<script src="https://use.fontawesome.com/releases/v5.14.0/js/all.js" data-auto-replace-svg="nest"></script>

in my base template. I think there's a significant amount of setup instructions currently missing in the docs.

sub dir

i am going to like pinax blog model post.
I have pinax blog in app/pinax/blog
And pinax like dont acess it.
In utils.py of pinax like have
Return "{0}.{1}".format(obj._meta.app_label, obj.meta.object_name)

Like

Since a like button usually lie in a detail page. Assume I have a blog post which URL is /post/4. When a anonymous user click the like boutton, he will redirect to the login page, with the url like
/accounts/login/next=?like/5/6. Once he login, a http get request send to that url, while we didn't implement the get method in our view, so a exception will be thrown.Do you think so?By the way, I didn't test it in real situation. I just analysis from the source code.

README AUTHENTICATION_BACKENDS need to quote value

In the README, the AUTHENTICATION_BACKENDS is noted as:
AUTHENTICATION_BACKENDS = [
# other backends
pinax.likes.auth_backends.CanLikeBackend,
]

however, I believe that the value must be wrapped in quotes, ie:
AUTHENTICATION_BACKENDS = [
# other backends
'pinax.likes.auth_backends.CanLikeBackend',
]

How to get model likes count?

Hello devs.
I am proudly using your package, but I have an issue.
I'd like to get my model's total likes programmatically, will be using this to list the entries with most likes.
Thank you.

help with errors

i get this errors when i like :
Method not allowed (get): /likes/like/7:2/

And this one:
Forbidden (CSRF token missing or icorret.)
Post 403

Call for Maintainers

Looking for maintainers!

There is a lot of pull requests and open issues that the current maintainers, myself included, are just not finding the time to properly get to.

Maybe you've submitted some PRs and are frustrated with the lack of attention. Maybe you use this project in one or more of your projects and want to see that it is properly carried forward.

Whatever you reasons may be, let me know if you have interest and I'll add you to the repo and to PyPI (will need your PyPI name).

Preference will go to those who have commits on this repo and/or have shown an active interest in the issues.

Thanks!
Patrick

phileo doesn't work with django 1.5 user models

CommandError: One or more models did not validate:
phileo.like: 'sender' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.

Solution is to have a fkey to settings.AUTH_USER_MODEL instead of auth.User.

405 Error

Getting 405 Error when clicking on like buttons. Scanned through codes, not sure what I did wrong (if any).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.