【发布时间】:2020-04-15 08:05:20
【问题描述】:
我需要什么
我正在为现有的 Django 项目开发一个拉取通知系统。从 100 多个视图开始,我正在寻找一种方法将参数(通知查询集)合并到所有视图中,因为这会呈现到我的 base.html 中,我可以通过将其传递到视图的参数字典中来做到这一点。
问题
我想在不编辑所有视图的情况下执行此操作,因为这会花费很长时间,并且所有未来的视图都需要包含此变量。
我的尝试
创建一个模板过滤器并将 request.user 作为变量传入以返回该用户的通知。这可行,但是当用户选择“新”通知时,我想向服务器发送一个信号,以将它们重定向到通知链接并将查看状态更改为“真”(POST 或 AJAX)。这需要特定视图知道如何处理该特定请求。
我的考虑
• 在 Django 中编辑最核心的“视图”。
我已尽力解释该问题,但如果需要更多信息,请随时询问。
谢谢!
models.py
class NotificationModel(models.Model):
NOTIFICATION_TYPES = {'Red flag':'Red flag'}
NOTIFICATION_TYPES = dict([(key, key) for key, value in NOTIFICATION_TYPES.items()]).items()
notification_type = models.CharField(max_length=50, choices=NOTIFICATION_TYPES, default='')
user = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(blank=True, null=True)
text = models.CharField(max_length=500, default='')
viewed = models.BooleanField(default=False)
views.py示例
class HomeView(TemplateView):
template_name = 'app/template.html'
def get(self, request, *args, **kwargs):
notifications = NotificationsModel.objects.filter(user=request.user)
args={'notifications':notifications}
return render(request, self.template_name, args)
def notification_handler(self, request)
if 'notification_select' in request.POST:
notification_id = request.POST['notification_id']
notification = NotificationModel.objects.get(id=notification_id)
notification.viewed = True
notification.save()
return redirect #some_url based on conditions
def post(self, request, *args, **kwargs):
notifications = self.notification_handler(request, *args, **kwargs)
if notifications:
return notifications
return self.get(self, request)
【问题讨论】:
-
我不明白这个问题,也许一些例子会有所帮助