如何通知所有用户?

时间:2015-02-03 13:10:39

标签: python django django-admin

我准备了一个通知应用程序。

我想向所有用户发送通知。 如果我使用这一行:

user = models.ForeignKey(User)

As at image

它使我有可能向用户发送我需要选择的通知。我想有一个选项,可以在同一时间向所有用户发送通知

models.py

from django.db import models
from django.contrib.auth.models import User

class Notifications(models.Model):
    title = models.CharField(max_length=150, verbose_name="Tytul")
    content = models.TextField(verbose_name="Wiadomosci")
    viewed = models.BooleanField(default=False, verbose_name="Otwarta")
    user = models.ForeignKey(User)

    def __unicode__(self):
        return self.title

views.py

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from models import Notifications

def show_notification(request, notification_id):
    n = Notifications.objects.get(id=notification_id)
    return render_to_response('notifications.html',{'notification':n})

def delete_notification(request, notification_id):
    n = Notifications.objects.get(id=notification_id)
    n.viewed = True
    n.save()

    return HttpResponseRedirect('/accounts/loggedin')

2 个答案:

答案 0 :(得分:0)

只需遍历所有用户并为每个用户创建通知:

from django.db import transaction

with transaction.atomic():
  for user in User.objects.all():
      Notifications.objects.create(title="some title", content="some content",
                                   user=user)

旁注:show_notification()delete_notification()存在安全问题。您向/显示/删除任何访问者的通知。用户添加过滤器,如下所示:

@login_required
def show_notification(request, notification_id):
    n = Notifications.objects.get(id=notification_id, user=request.user)
    ...

答案 1 :(得分:0)

要为每个用户添加通知,这是一个解决方案:

class Notifications(models.Model):
    [...]
    @classmethod
    def notify_all(klass, title, content):
        new_notices = list()
        for u in User.objects.all():
            new_notices.append(klass(user=u, title=title, content=content))
        klass.objects.bulk_create(new_notices)

然后,要执行此操作,请执行以下操作:

Notification.notify_all('Test title', 'Test message')