2015-02-03 5 views
1

알림 앱을 준비했습니다.모든 사용자에게 알림을 보내는 방법은 무엇입니까?

모든 사용자에게 알림을 보내고 싶습니다. 나는이 회선을 사용하는 경우 :

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') 
+0

.. . 질문이 뭐야? 각 사용자에 대한 알림 개체를 추가하는 방법 – dylrei

답변

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) 

사이드 노트 :에 보안 문제가 있습니다.및 delete_notification(). 방문자에게 /로 알림을 표시/삭제합니다. 같은 사용자가 필터를 추가

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

내가 필요로하는 것은 과장이 아니다. 첨부 된 내 인쇄 화면에서 제발 좀 봐 주 시겠어요 –

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') 
+0

고맙습니다. :)하지만이 줄을 어디에 추가해야합니까? Notification.notify_all ('테스트 제목', '테스트 메시지') –

+0

@ user3904216 알림을 트리거하는 코드의 마지막 줄을 호출 할 수 있습니다. 보기 일 수도 있고 다른 모델의 코드 일 수도 있습니다. 이러한 통지를 언제 어떻게 작성 하느냐에 달려 있습니다. – dylrei

+0

@ user3904216 이제 화면 캡을 보았습니다. 관리자를 통해이 작업을 수행하려면 ModelAdmin 양식에 일종의 확인란을 추가하거나 "모든"선택을 사용자 선택 위젯으로 밀어 넣을 수 있습니다. 그런 다음이 "all"신호를 확인하고 일반 관리자 저장을 단락시키고 대신 notify_all을 실행하십시오. ModelAdmin 및 관련 양식 사용자 정의 문서는 https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#modeladmin-methods – dylrei

관련 문제