我正在使用的代码:
class Message(models.Model):
from_who = models.ForeignKey(User, related_name='sent')
to = models.ForeignKey(User, related_name='recieved')
text = models.CharField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
new = models.BooleanField(default=True)
当我使用request.user 不上下文时,是否可以使用new = True在模板中显示User.recieved消息?如果是,怎么样?
答案 0 :(得分:1)
如果我理解了这个问题 - 您希望向登录用户显示所有新消息,而不向视图添加任何其他上下文?试试这个(并注意我更改了&#34的拼写;收到":
{% for message in request.user.received.all %}
{% if message.new %}
{{ message }}<br />
{% endif %}
{% endfor %}
答案 1 :(得分:0)
对于正在寻找答案的人:
#models.py
class Message(models.Model):
from_who = models.ForeignKey(User, related_name='sent')
to = models.ForeignKey(User, related_name='recieved')
text = models.CharField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
new = models.BooleanField(default=True)
new_messages = NewMessageManager()
#managers.py
class NewMessageManager(models.Manager):
def new_messages(self):
return super(NewMessageManager, self).get_queryset().filter(new=True)
#template.html
{% if request.user.recieved.new_messages %}
<span class="badge badge-danger">{{ request.user.recieved.new_messages.count }}</span>
{% endif %}