问题描述
我是初学者级别的Django开发人员,并且正在制作医院系统。在医院系统中,每当有任何患者上传有关医生ID的报告时,我都想添加一个通知系统。我想通知医生到医生通知模板,该患者(带有姓名)的报告已提交。
我试图使其工作2天,并使用信号创建了一条消息,但无法在医生那边显示。请任何人告诉我如何使它变得更容易,或者我应该使用其他方式代替信号。
我尝试过的以前的代码。
from django.shortcuts import render,HttpResponse,request
from hospital.models import Patient,Doctor,Report
from django.db.models.signals import post_save,pre_save
def save_report(sender,instance,**kwargs):
instance = Patient.objects.get(id=1)
dr_id= instance.assignedDoctorId
patient=models.Patient.objects.get(user_id=request.user.id)
doctor=models.Doctor.objects.get(id=dr_id)
notifications=print("New report has been submitted")
mydict={
'doctor':doctor,'patient':patient,'notifications':notifications
}
return render(request,'temp/doctor_Notifications.html',context=mydict)
post_save.connect(save_report,sender=Report)
解决方法
您应该创建通知模型,例如:
class Notification(models.Model):
person = models.ForeignKey(Mymodel,on_delete=models.CASCADE)
is_read = models.BooleanField(default=False)
message = models.TextField(max_length=100)
在您的视图中,只要患者发送报告,只需创建通知:
def save_report(sender,instance,**kwargs):
instance = Patient.objects.get(id=1)
dr_id= instance.assignedDoctorId
patient=models.Patient.objects.get(user_id=request.user.id)
doctor=models.Doctor.objects.get(id=dr_id)
Notification.objects.create(person=doctor,message=f'{instance} sent you a report!')
mydict={
'doctor':doctor,'patient':patient,}
return render(request,'temp/doctor_Notifications.html',context=mydict)
创建用于显示通知的视图,并在启动时切换为阅读:
class NotificationListView(ListView):
model = Notification
template_name = 'users/notifications.html'
def get_queryset(self):
notifications = Notification.objects.filter(person=self.request.user).all()
notifications.update(is_read=True)
return notifications
带有通知的模板:
{% block content %}
{% for notification in object_list %}
<h6>{{ notification.message }}</h6>
{% endfor %}
{% endblock %}
如果您的站点中有导航栏,则可能要显示未读通知的数量。您必须先过滤未读的通知: 在您的应用文件夹中,创建一个名为“ templatetags”的新文件夹,然后在其中创建: init .py和notifilter.py。
-yourApp
-templatetags
-__init__.py
-notifilter.py
notifilter.py
from django import template
register = template.Library()
@register.filter
def notifilter(args):
filtered = []
for i in args:
if i.is_read == False:
filtered.append(i)
return filtered
当您拥有导航栏并添加如下所示的行时,请在模板中加载过滤器:
{% load notifilter %}
<a class="nav-link" href="{% url 'notifications' %}">notifications({{ request.user.profile.notification_set.all|notifilter|length }})</a>