在django中为用户添加徽章以执行任务

时间:2018-05-12 14:02:27

标签: python django django-models django-templates django-views

你好Djangonauts,                 今天大家怎么样,我是Django的新手所以请原谅逻辑或代码中的任何愚蠢错误。我有一个用户,一个User_Profile和一个帖子模型。我想为用户发布的帖子数量提供用户徽章。例如,如果用户发布了3个帖子,他/她获得了初学者徽章,等等......

以下是用户个人资料models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_image = models.ImageField(default='', blank=True, null=True)
    badge_image = models.ImageField(default='', blank=True, null=True)#maybe default can be "static/images/beginner_image.jpg" but it does not work 

发布models.py

User = get_user_model()
class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts')
    title = models.CharField(max_length=250, unique=True)  
    slug = models.SlugField(allow_unicode=True, unique=True)
    message = models.TextField()

现在我希望实现这样的目标:

 user = User.objects.get(username=request.user.username)
    if user.posts.count >= 3 :
             badge_image = '<img src="some image">'# I don't know how to make a image variable in views and models. I know how to use it in Django templates with {{image.url}}   
    elif user.posts.count >= 20 :
             badge_image = '<img src="some image">'
    else:
         badge_image ='<img src="beginner_image">'

我在哪里可以在模型中,在视图中编写此代码?如果我的问题太基础,我很抱歉。我学到的项目都没有类似的情景

1 个答案:

答案 0 :(得分:4)

您可以在没有ImageField的情况下执行此操作。为此使用模型@property。您需要使用静态文件将徽章图像(例如badge_img1.jpgbadge_img2.jpg等)复制到导演(请查看文档how to manage static with Django)。像这样重写Profile

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_image = models.ImageField(default='', blank=True, null=True)

    @property
    def badge_image(self):
        if self.user.posts.count() >= 20:
             badge_image = 'badge_img1.jpg'# I don't know how to make a image variable in views and models. I know how to use it in Django templates with {{image.url}}   
        elif self.user.posts.count() >= 3:
             badge_image = 'badge_img2.jpg'
        else:
             badge_image ='badge_img3.jpg'
        return badge_image

您可以显示当前用户的图像:

{% load static %}
<img src={% static user.profile.badge_image %}>