python - Django 在模板中获取 ContentType

标签 python django django-templates django-contenttypes

我有一个页面,其中包含许多具有不同内容类型的对象。我需要有能力评价这个对象。这是它的一个类:

class Score(models.Model):
    user            = models.ForeignKey(User)

    content_type    = models.ForeignKey(ContentType)
    object_id       = models.PositiveIntegerField()
    for_object      = generic.GenericForeignKey('content_type', 'object_id')

    like            = models.BooleanField(default=True)
    created_at      = models.DateTimeField(auto_now_add=True, blank=True, null=True)

    comment         = models.CharField(max_length=255, blank=True, null=True)

    objects = ChainerManager(ScoreQuerySet)

    def __unicode__(self):
        return u'Score for (%s, #%s) from user %s at %s' %\
            (self.content_type, self.object_id, self.user.get_full_name(), self.created_at)

    class Meta:
        unique_together = (('user', 'content_type', 'object_id'),)

我的模板应该是这样的:

...
{% for random_object in random_object_queryset %}
<a href={% url like_object random_object.<content_type> random_object.id %}>{{ random_object.name }}</a>
<a href={% url dislike_object random_object.<content_type> random_object.id %}>{{ random_object.name }}</a>
{% endfor %}
...

我可以创建模板标签来获取它,或者获取类名,例如使用以下代码片段:http://djangosnippets.org/snippets/294/ 我可以重写此代码片段以获取对象的 content_type_id,但我担心在数据库中进行大量 CT 查找。

但是是否有一些嵌入式方法可以在模板中获取对象的 CT?

查看代码:

def rate_object(request, classname, object_id, like=True):
    user = request.user
    Klass = ContentType.objects.get(model=classname).model_class()
    obj = get_object_or_404(Klass, user=user, pk=object_id)

    try:
        score = Score.objects.for_object(user, obj)
        score.like = like
        score.save()
    except Score.DoesNotExist:
        score = Score.objects.like(user, obj) if like else Score.objects.dislike(user, obj)

    return HttpResponse(obj)

最佳答案

为了建立@Colleen 的答案,我最终使用了如下模板过滤器:

from django import template
from django.contrib.contenttypes.models import ContentType

register = template.Library()

@register.filter
def content_type(obj):
    if not obj:
        return False
    return ContentType.objects.get_for_model(obj)

然后像这样在模板中使用它:

{% load helpers %}
{% with instance|content_type as ctype %}
    <input type="hidden" name="content_type" value="{{ ctype.pk }}">
{% endwith %}

关于python - Django 在模板中获取 ContentType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12806276/

相关文章:

Python - SQL Server AWS Lambda 集成

python - 如何在 Django 模板中获取站点名称?

python - 使用Django 汇总Report

python - 如何使用 Windows 安装 pyPDF2 模块?

python - 有没有办法将参数传递给 optuna 中的多个工作?

python - 根据值将一列中的数据拆分为单独的列

django admin - 在带有中间表的多对多字段上使用水平过滤器

javascript - Django - 使用 block 仅重新加载正文页面而不刷新整个页面

javascript - 如何在 index.html 中传递变量以响应组件

Django buggy 模板标签 - 'NoneType' 对象没有属性 'source'