• Stars
    star
    316
  • Rank 132,587 (Top 3 %)
  • Language
    Python
  • License
    MIT License
  • Created almost 15 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

a badges app for Django

Pinax Badges

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.

Important Links

Where you can find what you need:

pinax-badges

Overview

As a reusable Django app, pinax-badges provides the ecosystem with a well tested, documented, and proven badges application for awarding badges to users in Django.

It provides simple abstractions over awarding users badges for completing tasks, including multi-level badges, and repeatable badges, making it super simple to add badges to a Django project.

Supported Django and Python Versions

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

Documentation

Installation

To install pinax-badges:

    $ pip install pinax-badges

Add pinax.badges to your INSTALLED_APPS setting:

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

Add pinax.badges.urls to your project urlpatterns:

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

Usage

pinax.badges.base.Badge

Pinax Badges works by allowing you to define your badges as subclasses of a common Badge class and registering them with pinax-badges. For example if your site gave users points, and you wanted to award three ranks of badges based on how many points a user had your badge might look like this:

    from pinax.badges.base import Badge, BadgeAwarded
    from pinax.badges.registry import badges

    class PointsBadge(Badge):
        slug = "points"
        levels = [
            "Bronze",
            "Silver",
            "Gold",
        ]
        events = [
            "points_awarded",
        ]
        multiple = False

        def award(self, **state):
            user = state["user"]
            points = user.get_profile().points
            if points > 10000:
                return BadgeAwarded(level=3)
            elif points > 7500:
                return BadgeAwarded(level=2)
            elif points > 5000:
                return BadgeAwarded(level=1)


    badges.register(PointsBadge)

There are a few relevant attributes and methods here.

slug

The unique identifier for this Badge, it should never change.

levels

A list of the levels available for this badge (if this badge doesn't have levels it should just be a list with one item). It can either be a list of strings, which are the names of the levels, or a list of pinax.badges.base.BadgeDetail which have both names and description.

events

A list of events that can possibly trigger this badge to be awarded. How events are triggered is described in further detail below.

multiple

A boolean specifying whether or not this badge can be awarded to the same user multiple times, currently if this badge has multiple levels this must be False.

award(self, **state)

This method returns whether or not a user should be awarded this badge. state is guaranteed to have a "user" key, as well as any other custom data you provide. It should return either a BadgeAwarded instance, or None. If this Badge doesn't have multiple levels BadgeAwarded doesn't need to be provided an explicit level.

Note: BadgeAwarded.level is 1-indexed.

Now that you have your PointsBadge class you need to be able to tell Pinax Badges when to try to give it to a user. To do this, any time a user might have received a badge just call badges.possibly_award_badge with the name of the event, and whatever state these events might need and Pinax Badges will handle the details of seeing what badges need to be awarded to the user:

    from pinax.badges.registry import badges

    def my_view(request):
        if request.method == "POST":
            # do some things
            request.user.profile.award_points(15)
            badges.possibly_award_badge("points_awarded", user=request.user)
        # more view

By default badges will be awarded at the current time, if you need to override the award time of the badge you can pass a force_timestamp keyword argument to possibly_award_badge().

Asynchronous Badges

Important To use asynchronous badges you must have celery installed and configured.

If your Badge.award() method takes a long time to compute it may be prohibitively expensive to call during the request/response cycle. To solve this problem Pinax Badges provides an async_ option to Badges. If this is True Pinax Badges will defer calling your award() method, using celery, and it will be called at a later time, by another process (read the celery docs for more information on how celery works).

Because award() won't be called until later you can define a freeze() method which allows you to provide and additional state that you'll need to compute award() correctly. This may be necessary because your Badge requires some mutable state.

    class AddictBadge(Badge):
        # stuff
        async_ = True

        def freeze(self, **state):
            state["current_day"] = datetime.today()
            return state

In this example badge the user will be awarded the AddictBadge when they've visited the site every day for a month, this is expensive to calculate so it will be done outside the request/response cycle. However, what happens if they visit the site right before midnight, and then the award() method isn't actually called until the next day? Using the freeze method you can provide additional state to the award() method.

Models

Module: pinax.badges.models

BadgeAward
  • user - The user who was awarded this badge.
  • awarded_at - The datetime that this badge was awarded at.
  • slug - The slug for the Badge that this refers to.
  • name - The name for the Badge this refers to, for the appropriate level.
  • description - The description for the Badge this refers to, for the appropriate level.

Signals

Module: pinax.badges.signals

pinax-badges makes one signal available to developers.

badge_awarded

This signal is sent whenever a badge is awarded to a user. It provides a single argument, badge, which is an instance of pinax.badges.models.BadgeAward.

Template Tags

Module: pinax.badges.templatetags.pinax_badges_tags

pinax-badges offers a number of template tags for your convenience, which are available in the pinax_badges_tags library.

badge_count

This tag returns the number of badges that have been awarded to this user, it can either set a value in context, or simple display the count. To display the count its syntax is:

    {% badge_count user %}

To get the count as a template variable:

    {% badge_count user as badges %}
badges_for_user

This tag provides a QuerySet of all of a user's badges, ordered by when they were awarded, descending, and makes them available as a template variable. The QuerySet is composed of pinax.badges.models.BadgeAward instances.

    {% badges_for_user user as badges %}

Templates

Templates are supplied by the user, in a pinax/badges/ subfolder in your project template search path.

badges.html

Lists all badges.

Context data: A sorted iterable of badge dictionaries keyed by badge slug:

"badges": 
[ 
    "<badge slug>": {
        "level": val,  # badge level
        "name": val,  # badge level name
        "description": val,  # badge level description
        "count": val,  # badge count
        "user_has": val,  # name and level of badges of this type earned by user
    },
]

badge_detail.html

Context data:

"badge": badge,  # badge to be displayed
"badge_count": badge_count,  # number of times it has been awarded
"latest_awards": latest_awards,  # most recent awards of badge

Change Log

3.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

2.0.3

  • Add Python 3.7 to the support versions matrix due to change made in v2.0.1
  • Change detox to tox --parallel

2.0.2

  • Don't fail when importing pinax.badges.tasks if celery is not installed.

2.0.1

  • Change Badge.async attribute to Badge.async_ since async is now a keyword in Python 3.7. This was implemented in a backwards compatible way so Badge.async is still valid in older Python versions.

2.0.0

  • Add Django 2.0 compatibility testing
  • Drop Django 1.8, 1.9, 1.10, and Python 3.3 support
  • Add application URL namespacing
  • Move documentation into README and standardize layout
  • Convert CI and coverage to CircleCi and CodeCov
  • Add PyPi-compatible long description

History

It was built by Eldarion as brabeion for use in Typewar and donated to Pinax in August 2017.

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.

More Repositories

1

pinax

a Django-based platform for rapidly developing websites
Python
2,624
star
2

django-user-accounts

User accounts for Django
Python
1,109
star
3

django-mailer

mail queuing and management for the Django web framework
Python
721
star
4

pinax-stripe-light

a payments Django app for Stripe
Python
677
star
5

pinax-blog

a blog app for Django
Python
461
star
6

symposion

a Django project for conference websites
Python
300
star
7

pinax-theme-bootstrap

A theme for Pinax based on Twitter's Bootstrap
HTML
269
star
8

pinax-referrals

a referrals app for Django
Python
208
star
9

pinax-messages

a Django app for allowing users of your site to send messages to each other
Python
197
star
10

django-forms-bootstrap

Bootstrap filter and templates for use with Django forms
Python
175
star
11

pinax-likes

a liking app for Django
Python
156
star
12

pinax-webanalytics

analytics and metrics integration for Django
Python
122
star
13

pinax-project-account

a starter project that incorporates account features from django-user-accounts
119
star
14

pinax-eventlog

An event logger
Python
108
star
15

pinax-invitations

a site invitation app for Django
Python
108
star
16

pinax-comments

a comments app for Django
Python
97
star
17

pinax-models

Provide Support for Logical Deletes on Models and in the Django Admin
Python
90
star
18

pinax-ratings

a ratings app for Django
Python
88
star
19

pinax-starter-projects

Pinax Starter Projects
Shell
79
star
20

django-flag

flagging of inapproriate/spam content
Python
73
star
21

django-waitinglist

DEPRECATED - please see https://github.com/pinax/pinax-waitinglist
Python
64
star
22

pinax-points

a points, positions and levels app for Django
Python
61
star
23

pinax-calendars

Django utilities for publishing events as a calendar
Python
61
star
24

pinax-documents

a document management app for Django
Python
59
star
25

pinax-teams

an app for Django sites that supports open, by invitation, and by application teams
Python
48
star
26

pinax-boxes

database-driven regions on webpages for Django
Python
48
star
27

pinax-starter-app

A starter app template for Pinax apps
Python
36
star
28

pinax-wiki

Easily add a wiki to your Django site
Python
32
star
29

pinax-project-symposion

a starter project demonstrating a minimal symposion instance
HTML
31
star
30

code.pinaxproject.com

the site behind code.pinaxproject.com
Python
29
star
31

pinax-forums

an extensible forums app for Django and Pinax
Python
27
star
32

pinax-project-zero

the foundation for other Pinax starter projects
25
star
33

pinax-waitinglist

a Django waiting list app
Python
25
star
34

pinax-testimonials

a testimonials app for Django
Python
24
star
35

pinax-project-teams

a starter project that has account management, profiles, teams and basic collaborative content.
18
star
36

pinax-images

an app for managing collections of images associated with a content object
Python
17
star
37

pinax-phone-confirmation

An app to provide phone confirmation via Twilio
Python
16
star
38

pinax-templates

semantic templates for pinax apps
HTML
15
star
39

pinax-project-socialauth

a starter project that supports social authentication
CSS
15
star
40

pinax-api

RESTful API adhering to the JSON:API specification
Python
13
star
41

pinax-submissions

an app for proposing and reviewing submissions
Python
12
star
42

pinax-project-blog

a blog starter project
10
star
43

pinax-project-forums

an out-of-the-box Pinax starter project implementing forums
HTML
10
star
44

pinax-images-panel

a React component for uploading and managing images with the pinax-images Django reusable app
JavaScript
9
star
45

pinax-cohorts

Create cohorts to invite to join your private beta site. Depends on pinax-waitinglist.
Python
9
star
46

pinax-pages

A light weight CMS born out of Symposion
Python
8
star
47

pinax-project-lms

A starter project to bring together components of the Pinax Learning Management System
CSS
7
star
48

pinax-cli

a tool for easily instantiating Pinax starter projects (django templates)
Python
7
star
49

django-site-access

an app to provide utilities via middleware to control access to your django site
Python
7
star
50

cloudspotting

a starter project allowing you to create collections of cloud images, view other peopleโ€™s collections, โ€œlikeโ€ a collection, etc.
CSS
7
star
51

pinax-calendars-demo

a demo project for pinax-calendars
Python
7
star
52

pinax-lms-activities

framework and base learning activities for Pinax LMS
Python
7
star
53

atom-format

Python
6
star
54

PinaxCon

PinaxCon is a project that demonstrates how Symposion can be hooked up for a conference site
HTML
6
star
55

pinax-events

a simple app for publishing events on your site
Python
5
star
56

pinax-news

a simple app for publishing links to news articles on your site
Python
5
star
57

pinax-utils

an app for Pinax utilities
Python
5
star
58

blog.pinaxproject.com

Python
5
star
59

pinax-types

Python
4
star
60

cloudspotting2

Pinax demo application showing many Pinax apps
CSS
4
star
61

pinax-project-static

3
star
62

pinax-cart

Python
3
star
63

pinax-identity

OpenID Connect with pinax-api helpers
Python
3
star
64

pinax-theme-classic

the original Pinax theme
HTML
3
star
65

pinax_theme_tester

a project based on the zero starter project used to test and build the pinax theme
Python
3
star
66

screencasts

2
star
67

pinax-project-wiki

a demo starter project for a single wiki site, featuring integration of pinax-wiki
2
star
68

lms-activities-demo

a Django site for demoing Pinax LMS Activities
Python
1
star
69

dashboard.pinaxproject.com

a collection of metrics and information about how the Pinax Project is going
Python
1
star
70

.github

Pinax Default Community Health Files
1
star
71

mytweets

a demo of pinax-types periods
Python
1
star
72

pinax-theme-pinaxproject

a Pinax theme for pinaxproject.com website
HTML
1
star
73

patch-game

guess the Pinax patch
CSS
1
star