我无法在我的项目中使用pinax徽章。我遵循了在我的应用程序中创建badges.py文件所提供的最小使用量example:
#badges.py
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)
和一个非常糟糕的点函数,在我的用户模型中调用a接受一个金额参数并将其添加到我的用户模型中的points字段。
#User Model
class User(AbstractUser):
....
points = models.IntegerField(default=0)
def award_points(self,amount):
self.amount = amount
self.points+=amount
self.save()
现在,我正在调用一个信号来检查用户登录的时间并给他们奖励一些积分。就像这样
#signal.py
from django.contrib.auth.signals import user_logged_in,user_logged_out
from django.dispatch import receiver
from django.conf import settings
from pinax.badges.registry import badges
@receiver(user_logged_in)
def award(sender,request ,user, **kwargs):
user = request.user.award_points(5000)
badges.possibly_award_badge("points_awarded", user=user)
我也注册了信号以确保。我仍然没有获得所需的结果,即,一旦用户登录并获得5000点,这足以获得badges.py文件中定义的1级徽章。 除了信号,我不确定有更有效的方法来实现这个结果,除非当然有人推荐一种不同的方法。
回应赞赏。
答案 0 :(得分:0)
这是我的表现。
在 models.py
中from django.template.defaultfilters import slugify
from django.db import models
from django.contrib.auth.models import User
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.profile.points
if points > 500:
return BadgeAwarded(level=3)
elif points > 50:
return BadgeAwarded(level=2)
elif points > 5:
return BadgeAwarded(level=1)
badges.register(PointsBadge)
class Profile(models.Model):
user = models.OneToOneField(
User,
on_delete = models.CASCADE
)
points = models.IntegerField (
default = 0
)
def award_points (self, points):
self.points += points
self.save()
在 signals.py 中,我在创建profile
时创建user
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
然后在我的view
request.user.profile.award_points(p.points)
badges.possibly_award_badge("points_awarded", user=request.user)