如何在Django模板中检查模型的名称

时间:2019-04-16 13:36:48

标签: django django-models

我正在尝试在模板中获取模型的名称,以便在模板中为其提供不同的设计

#views.py
class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html' 
    context_object_name = 'posts'
    paginate_by = 15

    def get_queryset(self):
        posts = []
        shared_post = []
        if self.request.user.is_authenticated:
            user_id = self.request.user.id
            view_user_post = Post.objects.filter(user=self.request.user)
            user_profile = User.objects.get(id=user_id).profile
            # print(user_profile)

            for profile in user_profile.follower.all():
                for post in Post.objects.filter(user=profile.user):
                    posts.append(post)

            for profile in user_profile.follower.all():
                for share in Share.objects.filter(user=profile.user):
                    shared_post.append(share)

            chain_qs = chain(posts, view_user_post, shared_post)
            print(chain_qs)
            return sorted(chain_qs, key=lambda x: x.date_posted, reverse=True)

        else:
            posts = Post.objects.all().order_by('?')
            return posts

#models.py
class Share(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField(max_length=140, null=True, blank=True)
    date_posted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return '{}- {}'.format(self.post.title, str(self.user.username))
class Post(models.Model):
    title = models.CharField(max_length=140)
    content = models.TextField(validators=[validate_is_profane])
    likes = models.ManyToManyField(User, related_name='likes', blank=True)
    date_posted = models.DateTimeField(default=timezone.now)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='post_pics', blank=True)
    image_2 = models.ImageField(upload_to='post_pics', blank=True)
    image_3 = models.ImageField(upload_to='post_pics', blank=True)
    restrict_comment = models.BooleanField(default=False)
    saved = models.ManyToManyField(User, related_name='saved_post', blank=True)

我需要一种方法来检查模板中模型的名称,可能需要一个if / else语句来进行正确检查。谢谢

2 个答案:

答案 0 :(得分:1)

如何在模型内部创建一个将返回模型名称的函数?

在您的模型.py中的每个模型内部:

def get_my_model_name(self):
    return self._meta.model_name

在您的模板中,您可以执行以下操作:

{%if post.get_my_model_name == 'post'%}
    Do something ...

答案 1 :(得分:0)

我建议您在每个模型中实现一个布尔属性,在一种情况下返回True,在另一种情况下返回False,而不是检查模型名称。例如:

class Post(models.Model):
    # whatever fields and methods

    @property
    def is_shared(self):
        return False


class Share(models.Model):
    # whatever fields and methods

    @property
    def is_shared(self):
        return True

然后在模板中检查{% if post.is_shared %}