使用filter(),如何获取当前经过身份验证的用户的外键属性“收件人”?
Models.py:
class Message(models.Model):
recipient = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'recipient',null = True)
sender = models.ManyToManyField(CustomUser,related_name = 'messages')
date = models.DateTimeField(auto_now_add=True, blank=True)
subject = models.CharField(max_length = 1000, blank = True)
message = models.TextField(blank=True, null=True)
unread = models.BooleanField(default = True)
class CustomUser(User):
user_bio = models.TextField(blank=True, null=True)
birth_date = models.DateField(null=True, blank=True)
def __str__(self):
return self.username
Views.py:
### Inbox list class
class InboxListView(ListView):
'''
This view lets the user view all the messages created in a list
'''
model = Message# [Message,SafeTransaction] # I want to be able to draw from two models/objects #
template_name = "myInbox/inbox.html"
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(InboxListView, self).get_context_data(**kwargs)
context['message_list'] = Message.objects.filter(recipient=CustomUser.SOMETHING_idk)#INCORRECT FILTRATION, FIX ASAP!!!!!!!!!!!!!#
context['now'] = timezone.now()
context['safeTransaction_list'] = SafeTransaction.objects.all()
return context
具体来说,这是我需要解决的问题:
context['message_list']=Message.objects.filter(recipient=CustomUser.SOMETHING_idk)
我可以将什么作为特定邮件收件人的过滤器参数? 我尝试了类似CustomUser或CustomUser.pk或request.authenticated_as_the_thing_I_want_specific的方法。等。
我似乎对此有点迷茫。
不胜感激。
答案 0 :(得分:3)
您似乎已创建了自定义身份验证用户模型?假设设置正确,您应该可以执行以下操作:
def get_context_data(self, **kwargs):
context = super(InboxListView, self).get_context_data(**kwargs)
context.update({
'message_list': Message.objects.filter(recipient=self.request.user),
'now': timezone.now(),
'safeTransactionList': SafeTransaction.objects.all(),
})
return context
一些其他注意事项:
now
作为django模板标记可用。您可以在模板代码中{% now %}
。{% for message in request.user.recipient.all %}
或{% for message in request.user.messages.all %}
中使用以下内容,而不用在get_context_data
中进行ORM调用来迭代{{ 1}}的登录用户。