这是我的代码:
MODEL
class compilation (models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=100, null=False, blank=False)
slot = models.PositiveIntegerField()
slotpergroup = models.PositiveIntegerField()
songs = models.ManyToManyField(song,related_name="slotsongs", null=True, blank=True)
class song(models.Model):
title = models.CharField(max_length=150)
content = models.FileField(upload_to='static/canzoni', validators=[validate_file_audio])
groups = models.ManyToManyField(group)
class group(models.Model):
user = models.ManyToManyField(User)
name = models.CharField(max_length=50)
genr = models.CharField(max_length=50)
avatar = models.FileField(upload_to='static/logogruppi', validators=[validate_file_extension])
查看
c = {}
compilation = compilation.objects.all()
c.update({'compilation': compilation })
return render_to_response('compilation.html', c, context_instance=RequestContext(request))
TEMPLATE compilation.html
{% for cd in compilation %}
{{ cd.title }}<br/>
PLAYLIST
{% for song in cd.songs.all %}
{{ song.title | capfirst }}<br/>
{% for g in song.groups.all %}
{{ g | capfirst }}
{% endfor %}
{% endfor %}
{% for gr in user.group_set.all %}
--> here my problem, I need something like this:
var = song.objects.filter(groups=gr).filter(slotsongs=cd).count()
if cd.slotpergropu <= var:
print: "all slots are busy for this group" <--
{% endfor %}
{% endfor %}
我需要针对每个用户组显示每个编辑,是否有可用的插槽,或者他的组中的某个人是否已经使用了所有可用的插槽。
答案 0 :(得分:0)
不幸的是,您无法调用需要模板中参数的函数。您必须在views.py
中组合所需内容,编写模板标记或过滤器。请查看documentation以了解详情。
答案 1 :(得分:0)
Django 通过不隐式允许模板中的任何Buseness逻辑来强制执行MVC框架。
根据标准这些事情应该在视图中完成,结果应该作为上下文传递给模板。
但是,如果有必要在模板中进行此查询,那么您可以将模板标记用于此目的,如下所示:
在此使用 Assginment标记:
{% load songs_tags %}
{% get_songs_for_group gr cd as var %}
创建模板标记文件
### templatetags/songs_tags.py ###
@register.assignment_tag
def get_songs_for_groups(group, collection):
return song.objects.filter(groups=group).filter(slotsongs=collection).count()
有关详细信息,请参阅文档:https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags