本文整理汇总了Python中notifications.models.Notification类的典型用法代码示例。如果您正苦于以下问题:Python Notification类的具体用法?Python Notification怎么用?Python Notification使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Notification类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: notifications_index
def notifications_index(request):
# get the page
page = int(request.GET.get('page', 1))
# Get the total pages (rounding up, ex: 1.2 pages means 2 pages)
total_pages = int(math.ceil(float(Notification.count(request.user)) / NOTIFICATIONS_PER_PAGE))
# If the page doesn't exists then 404
if page > total_pages and total_pages > 0:
raise Http404
# Get the notifications
offset = NOTIFICATIONS_PER_PAGE * (page - 1)
limit = offset + NOTIFICATIONS_PER_PAGE
notifications = Notification.find(request.user, offset, limit-1)
context = {
"total_pages": total_pages,
"actual_page": page,
"notifications": notifications
}
return render_to_response('notifications/notifications-index.html',
context,
context_instance=RequestContext(request))
开发者ID:slok,项目名称:dwarf,代码行数:25,代码来源:views.py
示例2: download_pdf
def download_pdf(request):
"""
request download of PDF file
- notify student of download
"""
results = {'success':False}
if(request.method == u'POST'):
try:
POST = request.POST
application = Application.objects.get(id=POST['application_id'])
documents = application.documents.all()
results['pdfs'] = [doc.url for doc in documents]
results['success'] = True
# notify user that application has been downloaded by company
try:
new_notification = Notification(user=application.user, company=application.company, receiver=1, notification=2)
new_notification.save()
except Exception, e:
print e
raise e
except:
pass
json_results = simplejson.dumps(results)
return HttpResponse(json_results, mimetype='application/json')
开发者ID:sanchitbareja,项目名称:occuhunt-web,代码行数:25,代码来源:views.py
示例3: post
def post(self, request, token=None):
user = check_token(token)
password = request.data.get('new_password', '')
if not password:
return Response(
dict(status="error", error_code="new_password_required",
message="You haven't provided a new password."))
# if we have a valid user
if user:
# check if the submitted password complies with the password_enforce_format
pass_check = password_enforce_format(password)
if pass_check:
user.set_password(password)
user.save()
return Response(
dict(status="error", error_code="invalid_password_format",
message=pass_check))
else:
package = dict(
caller='jwt_auth',
notification_type='RESET_PASSWORD_CONFIRMATION',
recipients=[user.email, ],
context=dict(
username=user.username,
password=password
)
)
notify = Notification(**package)
notify.send()
return Response(dict(status="success", message="Password has been successfully reset"))
else:
return Response(
dict(status="error", error_code="invalid_token",
message="The token you provided is invalid or has expired."))
开发者ID:vladblindu,项目名称:restserver,代码行数:35,代码来源:views.py
示例4: notify_handler
def notify_handler(verb, **kwargs):
"""
Handler function to create Notification instance upon action signal call.
"""
kwargs.pop('signal', None)
recipient = kwargs.pop('recipient')
actor = kwargs.pop('sender')
newnotify = Notification(
recipient = recipient,
actor_content_type=ContentType.objects.get_for_model(actor),
actor_object_id=actor.pk,
verb=unicode(verb),
public=bool(kwargs.pop('public', True)),
description=kwargs.pop('description', None),
timestamp=kwargs.pop('timestamp', now())
)
for opt in ('target', 'action_object'):
obj = kwargs.pop(opt, None)
if not obj is None:
setattr(newnotify, '%s_object_id' % opt, obj.pk)
setattr(newnotify, '%s_content_type' % opt,
ContentType.objects.get_for_model(obj))
if len(kwargs) and EXTRA_DATA:
newnotify.data = kwargs
newnotify.save()
开发者ID:Mondego,项目名称:pyreco,代码行数:29,代码来源:allPythonContent.py
示例5: notify_people
def notify_people(request, key, species, obj, users, metadata=None):
for user in users:
if request and user == request.user:
continue
n = Notification(key=key, species=species, linked_object=obj, user=user)
n.save()
if metadata:
n.set_metadata(metadata)
n.save()
try:
notification_restriction, __ = NotificationRestriction.objects.get_or_create(user=user, key=key)
except NotificationRestriction.MultipleObjectsReturned:
NotificationRestriction.objects.filter(user=user, key=key).delete()
notification_restriction, __ = NotificationRestriction.objects.get_or_create(user=user, key=key)
notification_restriction_all, __ = NotificationRestriction.objects.get_or_create(user=user, key='')
if notification_restriction.autoread or notification_restriction_all.autoread:
n.seen = True
n.save()
if not notification_restriction.no_email and not notification_restriction_all.no_email and Notification.objects.filter(key=key, species=species, object_id=obj.pk, content_type=ContentType.objects.get_for_model(obj), user=user, seen=False).count() == 1:
NotificationEmail(user=user, notification=n).save()
开发者ID:AnomalRoil,项目名称:truffe2,代码行数:28,代码来源:utils.py
示例6: NotificationTests
class NotificationTests(TestCase):
def setUp(self):
settings.NOTIFICATION_OPTIONS = dict(
TEST_NOTIFICATION=dict(
caller='notification',
template='notification_test_template.html',
subject='Notification test template'
)
)
self.package = dict(
caller='notifications',
notification_type='TEST_NOTIFICATION',
recipients=['[email protected]_host.com', ],
context=dict(
dummy_data='dummy_data'
)
)
# noinspection PyUnresolvedReferences
def tearDown(self):
del settings.NOTIFICATION_OPTIONS
# noinspection PyUnresolvedReferences
def test_notification_options(self):
self.notification = Notification(**self.package)
self.notification.send()
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'Notification test template')
self.assertTrue('dummy_data' in mail.outbox[0].body)
开发者ID:vladblindu,项目名称:restserver,代码行数:30,代码来源:tests.py
示例7: register_view
def register_view(request):
form = UserRegistrationForm(request.POST or None, request.FILES or None)
if request.user.is_authenticated():
return redirect('login_view')
if request.method == 'POST':
if form.is_valid():
form.save()
email = form.cleaned_data['email']
password = form.cleaned_data['password1']
activation_key = signing.dumps({'email': email})
user = User.objects.get(email=email)
UserActivation.objects.filter(user=user).delete()
new_activation = UserActivation(user=user, activation_key=activation_key,
request_time=timezone.now())
new_activation.save()
mailing.confirm_email(email, activation_key)
notification = Notification(user=user,
text='Пожалуйста, активируйте ваш профиль, перейдя по ссылке в письме на вашем почтовом ящике')
notification.save()
user = auth.authenticate(username=email, password=password)
auth.login(request, user)
return redirect('index_view')
else:
messages.warning(request, "Здесь есть неверно заполненные поля!")
return render(request, 'reg.html', {'form': form})
return render(request, 'reg.html', {'form': form})
开发者ID:vitaliyharchenko,项目名称:sportcourts2,代码行数:30,代码来源:views.py
示例8: notify_user
def notify_user(recipient, actor, verb, **kwargs):
"""
Handler function to create Notification instance upon action signal call.
"""
new_notification = Notification(
recipient = recipient,
actor_content_type=ContentType.objects.get_for_model(actor),
actor_object_id=actor.pk,
verb=text_type(verb),
public=bool(kwargs.pop('public', False)),
description=kwargs.pop('description', None),
timestamp=kwargs.pop('timestamp', utc_now()),
level=kwargs.pop('level', Notification.LEVELS.info),
)
for opt in ('target', 'action_object'):
obj = kwargs.pop(opt, None)
if not obj is None:
setattr(new_notification, '%s_object_id' % opt, obj.pk)
setattr(new_notification, '%s_content_type' % opt,
ContentType.objects.get_for_model(obj))
if len(kwargs) and EXTRA_DATA:
new_notification.data = kwargs
new_notification.save()
return new_notification
开发者ID:omni360,项目名称:inspiration-edu-api,代码行数:29,代码来源:tasks.py
示例9: follow
def follow(self, user):
self.followed_users.add(user)
self.add_redis_set.delay('followed_users', user.id)
self.add_feeds_from_user.delay(user)
user.add_redis_set.delay('followers', self.id)
if user.notify_new_friend:
note = Notification(sender=self, recipient=user, note_type=0, subject_id=self.id)
note.save()
开发者ID:wangjiaji,项目名称:heartbeat,代码行数:8,代码来源:models.py
示例10: render
def render(self, context):
try:
n = Notification()
context[self.var_name] = n.is_notified(self.notification_name,
context['user'])
except:
pass
return ""
开发者ID:joskid,项目名称:tbonline,代码行数:9,代码来源:notification_tags.py
示例11: amo_notification
def amo_notification(instance, **kw):
""" Given an error see if we need to send a notification """
log('Firing signal: default_notification')
user = User.objects.get(email__in=amo_users)
if instance.domain in amo_domains:
notification = Notification()
notification.notifier = instance
notification.save()
notification.user.add(user)
开发者ID:andymckay,项目名称:arecibo-mozilla,代码行数:10,代码来源:emails.py
示例12: testBasic
def testBasic(self):
c = Client()
assert not Error.all().count()
c.post(reverse("error-post"), test_data)
assert test_data["priority"] < 5, test_data["priority"]
assert Error.all().count() == 1
assert Notification.all().count() == 1
c.post(reverse("error-post"), test_data)
assert test_data["priority"] < 5, test_data["priority"]
assert Error.all().count() == 2
assert Notification.all().count() == 2
开发者ID:alanjds,项目名称:arecibo,代码行数:12,代码来源:tests.py
示例13: custom_notification
def custom_notification(by,body,subject,superusers = True):
if superusers:
users = User.objects.filter(is_superuser=True)
for user in users:
context = {'user': user.name, 'body': body, 'subject': subject}
emailit.api.send_mail(user.email,
context,
'notification/emails/notification_email',
from_email=user.email)
notif = Notification(actor=by, recipient=user, verb=subject, description=body, emailed=True)
notif.save()
return True
开发者ID:glosoftgroup,项目名称:Hardware,代码行数:12,代码来源:views.py
示例14: default_notification
def default_notification(instance, **kw):
""" Given an error see if we need to send a notification """
log("Firing signal: default_notification")
# todo, this will be changed to lookup a user profile as per
# http://github.com/andymckay/arecibo/issues/issue/4
if instance.priority >= 5:
return
notification = Notification()
notification.error = instance
notification.user = [ str(u.key()) for u in approved_users() ]
notification.save()
开发者ID:alanjds,项目名称:arecibo,代码行数:13,代码来源:listeners.py
示例15: create
def create(cls, *args, **kwargs):
task = cls(*args, **kwargs)
task.save()
from misc.models import Search # bidirectional import
Notification.create(
users=task.course.students,
heading='New task created',
text='{} created in {}'.format(task.name, task.course.name),
url=reverse('viewtask', args=(task.id,))
)
Search.add_words(kwargs['name'], task.id, Task)
return task
开发者ID:matts1,项目名称:Kno,代码行数:13,代码来源:base.py
示例16: page
def page(request):
if request.POST:
if "cancel" in request.POST:
return HttpResponseRedirect(reverse_lazy('index'))
else:
form = NewUserModel(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
surname = form.cleaned_data['surname']
email = form.cleaned_email() # TODO: all email on lower
pas2 = form.cleaned_data['password2']
tel = form.cleaned_data['phone']
new_user = UserModel(
email=email.lower(),
is_active=True,
name=name,
surname=surname,
phone=tel,
messages=1)
new_user.set_password(pas2)
# TODO: play with commit False.
# If captcha fails creates user anyways.
try:
taken = UserModel.objects.get(email=email.lower())
except UserModel.DoesNotExist:
new_user.save()
new_notification = Notification(
user=new_user,
notified=False,
text=u"""Welcome to the website!
You have an available account.""")
new_notification.save()
messages.success(request, 'New user created correctly.')
# TODO: authenticate user otherwise next will always go to index
if request.user.is_anonymous:
return HttpResponseRedirect(reverse_lazy('index'))
else:
if request.user.is_admin:
return HttpResponseRedirect(reverse_lazy('users_list'))
else:
return HttpResponseRedirect(reverse_lazy('panel'))
else:
return render(
request,
'clients/user_create.html',
{'form': form}
)
else:
form = NewUserModel()
return render(request, 'clients/user_create.html', {'form': form})
开发者ID:pilamb,项目名称:djangoShop,代码行数:51,代码来源:forms.py
示例17: create
def create(cls, task, user, bonus):
sub = cls.objects.filter(user=user, task=task).first()
if sub is None:
sub = AssignSubmission(user=user, task=task, criteria=None, data=bonus['data'], mark=0)
else:
sub.data = bonus['data']
sub.save()
Notification.create(
users=[task.course.teacher],
heading='Task handed in',
text='{} handed in for {}'.format(user.get_full_name(), task.name),
url=reverse('viewtask', args=(task.id,))
)
return sub.on_submit(bonus)
开发者ID:matts1,项目名称:Kno,代码行数:14,代码来源:assign.py
示例18: approve_user
def approve_user(request, approve_key):
key = str(base64.b64decode(approve_key))
user = get_object_or_404(User, pk = int(key.split("_")[0]))
group = get_object_or_404(GroupProfile, pk = int(key.split("_")[1]))
try:
user.groups.add(group.group)
GroupPermission(group=group.group, user=user, permission_type=2).save()
messages.add_message(request, messages.INFO, "Your approval is successful!")
notification = Notification(text = \
"Manager of the group %s has just approved you to join.\n Click on the following link to go to that group: http://%s/group/%s/ \n \
Have fun!" % (group.group.name, get_domain(), group.slug), entity=group, recipient = user)
notification.save()
except:
pass
return HttpResponseRedirect('/')
开发者ID:dibaunaumh,项目名称:Ecclesia,代码行数:15,代码来源:views.py
示例19: handle
def handle(self, *args, **options):
today = date.today()
to_notify = EmptyQuerySet()
# Iterate over sales that are in effect
for sale in Sale.objects.filter(start__lte=today,
end__gte=today):
# Find subscriptions that require the products on sale
subscriptions = Subscription.objects.filter(product__in=sale.products.all())
# Remove subscriptions that have been notified
subscriptions = subscriptions.exclude(notifications__sale=sale)
to_notify |= subscriptions
# Collect the subscriptions by user
user_subs = defaultdict(list)
for sub in to_notify:
user_subs[sub.user].append(sub)
from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', '[email protected]')
# Build the emails
for user, subs in user_subs.iteritems():
to_email = user.email
context = {'user': user, 'subscriptions': subs}
subject = render_to_string('notifications/sale_subject.txt', context).replace('\n', '').strip()
context['subject'] = subject
text_content = render_to_string('notifications/sale_body.txt', context)
html_content = render_to_string('notifications/sale_body.html', context)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
msg.attach_alternative(html_content, 'text/html')
msg.send() # Will raise exceptions on failure
# Mark all active sales for this product as notified
for sub in subs:
for sale in sub.product.active_sales.all():
notified = Notification()
notified.sale = sale
notified.subscription = sub
notified.save()
开发者ID:Mustack,项目名称:LoLSales,代码行数:48,代码来源:salesnotify.py
示例20: notifications_send
def notifications_send(request):
log("Firing cron: notifications_send")
notifications = Notification.all().filter("type = ", "Error").filter("tried = ", False)
# batch up the notifications for the user
holders = {}
for notif in notifications:
for user in notif.user_list():
key = str(user.key())
if key not in holders:
holder = Holder()
holder.user = user
holders[key] = holder
holders[key].objs.append(notif.notifier())
holders[key].notifs.append(notif)
for user_id, holder in holders.items():
try:
send_error_email(holder)
for notification in holder.notifs:
notification.tried = True
notification.completed = True
notification.save()
except:
info = sys.exc_info()
data = "%s, %s" % (info[0], info[1])
for notification in holder.notifs:
notification.tried = True
notification.completed = True
notification.error_msg = data
notification.save()
return render_plain("Cron job completed")
开发者ID:andymckay,项目名称:arecibo,代码行数:34,代码来源:views.py
注:本文中的notifications.models.Notification类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论