自定义django模板标记/参数忽略条件

时间:2012-07-11 20:03:42

标签: django django-views django-templates

我有一个Event课程。活动有presenterspresenters被放入“参加者”列表中。演示者应该有一个标记,显示他们实际上是与会者列表中的演示者。即:在他们的头像{% if is_presenter %}旁边的复选标记。截至目前,它正在为所有与会者添加一个复选标记。

我只希望该标志仅显示presenters。我究竟做错了什么?我如何添加复选标记只显示给那些呈现? (另外,我不知道我的头衔是否适合这种情况。让我知道。)

型号:

class Event(models.Model):
    title = models.CharField(max_length=200)
    presenters = models.ManyToManyField(Profile, null=True, blank=True)
    url = models.CharField(max_length=200)
    description = models.TextField()
    date = models.DateTimeField()
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    tags = models.ManyToManyField(Tag, null=True, blank=True)

class Attendee(models.Model):
    event = models.ForeignKey(Event)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    profile = generic.GenericForeignKey('content_type', 'object_id')

查看:

def event(request, id):
    event = get_object_or_404(Event, id=id)
    is_attending = False
    is_presenter = False
    if request.user.is_authenticated():
            profile = Profile.objects.get(user=request.user)
        attendees = [a.profile for a in Attendee.objects.filter(event=event)]
        if profile in attendees:
            is_attending = True        
    for presenter in event.presenters.all():
        is_attending = True
        try:
            content_type = ContentType.objects.get(app_label='profiles', model='profile')
            Attendee.objects.get(event=event, content_type=content_type, object_id=presenter.id)
            is_presenter = True
        except Attendee.DoesNotExist:
            Attendee(event=event, profile=presenter).save()

模板:

{% for attendee in event.attendees %}
     <div class="inline-block">   
        <a href="/profile/{{ attendee.profile.get_type|lower}}/{{ attendee.profile.user.username }}"{% if attendee.profile.is_presenter %}title="Presenter" class="tooltip-below"{% endif %}>
        <img width=30 height=30 src="{% if attendee.profile.avatar %}{% thumbnail attendee.profile.avatar 30x30 crop %}{% else %}{{ DEFAULT_AVATAR }}{% endif %}" />
        </a>
        {% if is_presenter %}
            <i class="icon-ok-sign"></i>
        {% endif %}
    </div>
{% endfor %}

1 个答案:

答案 0 :(得分:0)

我不理解你的问题。但似乎问题是你的is_presenter标志不是你对象的属性。因为python允许以dinamically方式创建属性,解决方案可能是以这种方式将此boolean var设置为模型:

    ...
    if profile in attendees:
        profile.is_attending = True  
for presenter in event.presenters.all():
    presenter.is_attending = True

在模板中:

    {% if profile.is_presenter %}

*优雅的解决方案是使用is_presenter()方法扩展个人资料模型。*