def answer_written_notify(self, answer_id): try: # For the question asker a = Answer.objects.get(pk=answer_id) # For users following the question question = a.question qf = QuestionFollowing.objects.filter(question=question) for user in qf: n = Notification(actor_id=a.writer.id, owner_id=user.user.id, note_type=12, notification_id=answer_id) n.save() # For users who turned on notifications to the writer notification_subscribed_users = UserTurnedOnNotifications.objects.filter( user=a.writer.user).values('subscriber').select_related() for user in notification_subscribed_users: n = Notification(actor_id=a.writer.id, owner_id=user.user.id, note_type=2, notification_id=answer_id) except Exception as e: self.retry(exc=e, countdown=60)
def create(request): if not request.user.is_authenticated: return redirect('login') profile=Profile.objects.get(user=request.user) if not profile.isTeacher: messages.add_message(request,messages.ERROR, "Only teachers can create sessions!") return redirect('profile') template="createsession.html" if request.method=="POST": s=Session() form=CreateSessionForm(request.POST, instance=s) if form.is_valid(): s=form.save() n=Notification( title='Session Created', text=profile.getName()+ ' has created a new session on '+s.date.strftime("%d/%m/%Y at %H:%M")+". Please review it as soon as possible.", target=s.student.profile, link="/school/session/"+str(s.id), css="warning" ) n.save() n=Notification( title='Session Created', text=profile.getName()+ ' has created a new session on '+s.date.strftime("%d/%m/%Y at %H:%M")+". If you wish to make any requests prior to the session, this is the time to do so.", target=s.student.parent, link="/school/session/"+str(s.id), css="warning" ) n.save() return redirect('profile') else: form=CreateSessionForm() form.teacher= profile.Teacher context={"form":form, "students":profile.Teacher.Students} return render(request,template,context)
def QuizSubmitView(request, course_slug, lesson_slug): if request.method == 'POST': course = Course.objects.get(slug=course_slug) lesson = Lesson.objects.get(slug=lesson_slug) quiz = Quiz.objects.get(lesson__slug=lesson.slug) quizquestionanswers = Question.objects.filter( quiz__title=quiz.title)[:10] quizscore = 0 quizform = request.POST.copy() processedquiz = {} for quizquestionanswer in quizquestionanswers: processedquiz[f'q{quizquestionanswer.id}'] = quizform[f'q{quizquestionanswer.id}'] if processedquiz[f'q{quizquestionanswer.id}'] == quizquestionanswer.answer: quizscore += 1 else: quizscore += 0 try: quizparticipation = QuizParticipation.objects.get( quiz__title=quiz.title, participator__username=request.user.username) if quizparticipation: print(quizparticipation) schedule_next = quizparticipation.participate_next - \ datetime.datetime.now(tz=timezone.utc) if schedule_next.days > 7: quizparticipation.quiz = quiz quizparticipation.quiz_score = quizscore quizparticipation.participate_date = datetime.datetime.now( tz=timezone.utc) quizparticipation.participate_next = datetime.datetime.now(tz=timezone.utc) + \ datetime.timedelta(days=7) quizparticipation.save() messages.success( request, 'Thank you for your reparticipation') notification = Notification() notification.title = f'Thankyou for your participation in { quiz.title }' notification.message = f'You scored: {quizparticipation.quiz_score}. You can participate after {quizparticipation.participate_next}' notification.user = request.user notification.save() return redirect('courses:lesson-detail', course_slug, lesson_slug) else: messages.success( request, 'You can not retake within 7 days') return redirect('courses:lesson-detail', course_slug, lesson_slug) except: quizparticipation = QuizParticipation() quizparticipation.quiz = quiz quizparticipation.quiz_score = quizscore quizparticipation.participate_date = datetime.datetime.now( tz=timezone.utc) quizparticipation.participate_next = datetime.datetime.now(tz=timezone.utc) + \ datetime.timedelta(days=7) quizparticipation.participator = request.user quizparticipation.save() messages.success(request, 'Thank you for your participation') notification = Notification() notification.title = f'Thankyou for your participation in { quiz.title }' notification.message = f'You scored: {quizparticipation.quiz_score}. You can participate after {quizparticipation.participate_next}' notification.user = request.user notification.save() return redirect('courses:lesson-detail', course_slug, lesson_slug)
def create(self, validated_data): try: user = self.perform_create(validated_data) except IntegrityError: self.fail('cannot_create_user') Notification().greeting(user) Notification().new_user(user, validated_data['password']) return user
def replyCreate_view(request): if request.method == "POST": parent_obj = None try: account = Account.objects.get(user=request.user) parent_id = int(request.POST.get('parent_id')) content = request.POST.get('reply') post = Post.objects.get(slug=request.POST.get('post_slug')) except: parent_id = None if parent_id: parent_obj = Comment.objects.get(id=parent_id) if parent_obj: reply_comment = Comment() reply_comment.account = account reply_comment.post = post reply_comment.content = content reply_comment.parent = parent_obj reply_comment.save() post.comments += 1 post.save() # notify to the comment owner if parent_obj.account != reply_comment.account: content = reply_comment.account.user.first_name + ' ' + reply_comment.account.user.last_name + ' replied to your comment "' + reply_comment.content[: 20] + '"' notf = Notification() notf.account = parent_obj.account notf.post = post notf.content = content notf.save() # notify others who also replied to the comment avoiding repeatation... marked = [] replies = parent_obj.replies.all() for replied in replies: if replied.account.user.email not in marked: if reply_comment.account != replied.account and parent_obj.account != replied.account: # don't notify the replier him/her-self content = reply_comment.account.user.first_name + ' ' + reply_comment.account.user.last_name + ' also replied on ' + parent_obj.account.user.first_name + "'s comment " + '"' + reply_comment.content[: 20] + '"' notf = Notification() notf.account = replied.account notf.post = post notf.content = content notf.save() marked.append(replied.account.user.email) return HttpResponseRedirect(post.get_absolute_url) return HttpResponseRedirect('/posts/')
def user_like_post(sender, instance, *args, **kwargs): like = instance post = like.post sender = like.user notify = Notification(post=post, sender=sender, user=post.user, notification_type=1) notify.save()
def user_follow(sender, instance, *args, **kwargs): follow = instance sender = follow.follower following = follow.following notify = Notification(sender=sender, user=following, notification_type=3) notify.save()
def like_view(request, slug): if request.method == "POST": post = Post.objects.get(slug=slug) account = Account.objects.get(user=request.user) qs = Like.objects.filter(post=post).filter(account=account) if not qs.exists(): like = Like() like.account = account like.post = post like.save() post.likes += 1 post.save() if like.account != post.account: notf = Notification() notf.account = post.account notf.post = post content = like.account.user.first_name + ' ' + like.account.user.last_name + ' liked your post.' notf.content = content notf.save() else: like = Like.objects.get(post=post, account=account) like.delete() post.likes -= 1 post.save() return HttpResponseRedirect(post.get_absolute_url) return HttpResponseRedirect('/posts/')
def markpaid(request,id): if not request.user.is_authenticated: return redirect('login') profile= Profile.objects.get(user=request.user) if not profile.isTeacher: return redirect('profile') try: session = Session.objects.get(id=id) except Session.DoesNotExist: messages.add_message(request,messages.ERROR, "Session does not exist!") return redirect('profile') if not session.teacher==profile.Teacher: messages.add_message(request,messages.ERROR, "Thats not your session!") return redirect('profile') session.paid=True session.save() messages.add_message(request, messages.SUCCESS, "Session marked as paid!") n=Notification( title='Payment Confirmation', text="This is a confirmation of "+profile.getName()+ ' receiving the payment of £'+str(session.cost)+' for the session on '+session.date.strftime("%d/%m/%Y at %H:%M")+".", target=session.student.parent, link="/school/session/"+id, css="success" ) n.save() return redirect('profile')
def send_notification(self, notification_subscription, type): if Notification.objects.filter( notification_subscription=notification_subscription, type=type).exists(): return None if type == NOTIFICATION_TYPE.ONE_HOUR: msg = f'Raffle {notification_subscription.raffle.name} will start in 1 hour' elif type == NOTIFICATION_TYPE.ONE_MINUTE: msg = f'Raffle {notification_subscription.raffle.name} will start in 1 minute' elif type == NOTIFICATION_TYPE.HAS_STARTED: msg = f'Raffle {notification_subscription.raffle.name} has started' elif type == NOTIFICATION_TYPE.HAS_ENDED: msg = f'Raffle {notification_subscription.raffle.name} has ended' else: return None url = f'https://poap.fun/{notification_subscription.raffle.id}' response = self.send_fcm(notification_subscription.token, msg, url) notification = Notification( notification_subscription=notification_subscription, type=type, response=response) notification.save()
def sample_ajax_view(request, cid): print(cid) print(request.user) id = request.user currentuser = request.user.id if currentuser == cid: print("sameuser") pass else: print("differentuser") different = Notification.objects.order_by('-date').filter( sender=request.user.id).filter(receiver_id=cid) if different: print("tablilund") pass else: print("add cheythu") msg = Notification(sender=request.user, receiver_id=cid) msg.save() realtor = UserProfile.objects.all().values('phone').filter(user=cid) data = list(realtor) return JsonResponse(data, safe=False)
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()
def likePost(request, post_key): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id post = Posts.objects.get(pk=post_key) if post.likes: if person_id in post.likes['persons']: post.likes['persons'].remove(person_id) isLiked = False else: post.likes['persons'].append(person_id) isLiked = True else: post.likes = dict(persons=[(person_id)]) isLiked = True post.save() # make a notification to send if post.person_id != person_id and isLiked: notification = Notification( noti=0, person_for=post.person_id, person_from=person_id, about=post.id, created=datetime.now().timestamp() ) notification.save() return Response(json.loads('{"action":"success"}'),status=status.HTTP_200_OK)
def save(self, *args, **kwargs): if self._state.adding: """ check this: https://stackoverflow.com/questions/18732111/django-bulk-create-for-models-with-multiple-required-fields """ content = "Someone has posted an item in room " else: content = "Someone has updated an item in room " super().save(*args, **kwargs) room = self.section.room students = room.students.all() teachers = room.teachers.all() members = students | teachers content = content + room.course.title + ", " + room.course.details + " section " + self.section.title + "." content_type = "item, " + str(room.id) + ", " + str(self.id) Notification.objects.bulk_create([ Notification(user=user, content=content, content_type=content_type) for user in members ])
def save(self, *args, **kwargs): if self._state.adding: content = "Someone has posted a comment in room " else: content = "Someone has updated a comment in room " super().save(*args, **kwargs) section = self.item.section room = section.room students = room.students.all() teachers = room.teachers.all() members = students | teachers item_content = self.item.content if (len(item_content) > 12): item_content = item_content[0:12] item_content += "... " content = content + room.course.title + ", " + room.course.details + " section " + section.title + " item " + item_content content_type = "comment, " + str(room.id) + ", " + str(self.item.id) Notification.objects.bulk_create([ Notification(user=user, content=content, content_type=content_type) for user in members ])
def newOrder_view(request): template_name = 'orders/confirmed-page.html' if request.method == "POST": cartKey = request.POST['cart'] phone = request.POST['cell'] order_type = request.POST['orderType'] account = None if request.user.is_authenticated: account = Account.objects.get(user=request.user) else: qs = Account.objects.filter(phone=phone).exists() if qs: account = Account.objects.get(phone=phone) order = Order() order.account = account try: cart = Cart.objects.get(key=cartKey) cart.is_active = True cart.save() order.cart = cart except: messages.warning(request, "Order request failed! Please try again.") return HttpResponseRedirect('/restaurants/' + cart.restaurant.slug + '/') _discount = 0.00 try: dObj = Discount.objects.get(key=request.POST['promoCode']) if dObj.used == False: _discount = int( float(cart.subtotal * dObj.percentage) / 100.00) dObj.used = True dObj.save() except: pass order.name = request.POST['name'] order.phone = phone order.shipping_address = request.POST['location'] order.order_type = order_type order.payment_method = request.POST['paymentMethod'] order.expected_time = request.POST['time'] if order_type == 'home': order.cost = cart.total - _discount + 30.00 # Shipping cost else: order.cost = cart.total - _discount order.discount = _discount order.save() # SEND NOTIFICATION if account != None: notification = Notification() notification.account = account notification.content = "You order <span class='font-weight-bold'>#" + str( order.order_no ) + "</span> has been added. We will confirm it in minutes." notification.link = '/orders/' + order.order_id + '/' notification.save() return HttpResponseRedirect('/orders/' + order.order_id + '/') messages.warning(request, "Something went wrong. Please try again.") return HttpResponseRedirect('/restaurants/' + cart.restaurant.slug + '/')
def setUp(self): self.seller = _set_up_seller() self.first_notification = Notification( seller=self.seller, amount=965.0, average_sales=966.67, notification_date=datetime.now()) self.first_notification.save() self.second_notification = Notification( seller=self.seller, amount=1000.0, average_sales=1010.0, notification_date=datetime.now()) self.second_notification.save()
def setup_testing_notifications(user): from notifications.models import Notification Notification(pk=1, key="mynotifkey", species="moderation", linked_object=user, user=user).save()
def handle(self, *args, **options): now = timezone.now() pjs = ProfileJob.objects.all() for pj in pjs: date_next = pj.assign_at + timedelta(days=1) exist_history = JobHistory.objects.filter(profilejob=pj).exists() print "FECHA ACTUAL: %s >= F24H:%s, %s, %s " % (now, date_next, (now >= date_next), exist_history) if (date_next <= now) and not exist_history: print "Creando notificacion" if not Notification.objects.filter( obj='ProfileJob', obj_id=pj.id, profile=pj.profile).exists(): notification = Notification( profile=pj.profile, level=u'HIG', type=u'MES', title=u'Trabajo no cumplido por: %s' % (pj.profile), content=u'No se ha realizado el trabajo con estado %s' % (pj.job.state), obj=u'ProfileJob', obj_id=(u'%s' % pj.id), ) notification.save()
def reactionWow(request, id): if not request.user.is_authenticated(): raise Http404 product = get_object_or_404(Product, id=id) if (request.user in product.likes.all()): product.likes.remove(request.user) if (request.user in product.smiles.all()): product.smiles.remove(request.user) if (request.user in product.wishes.all()): product.wishes.remove(request.user) if request.user.id != product.store.user.id: notif = Notification(from_user=request.user, to_user=product.store.user, notification_type='W', product=product) notif.save() product.wishes.add(request.user) product.save() print("reaction --Wow-- added successfully from reactions application...") return HttpResponse(product.likes.count() + product.smiles.count() + product.wishes.count())
def updateStatus_view(request, order_id): if not request.user.is_staff or not request.user.is_superuser or request.method != "POST": return HttpResponseRedirect('/404notfound/') try: order = Order.objects.get(order_id=order_id) if order.status == True: order.status = False notf = "Order #" + str(order.order_no) + " is pending." elif order.status == False: order.status = True notf = "Order #" + str(order.order_no) + " is accepted." order.save() except: messages.success(request, "Couldn't change status.") pass # SEND NOTIFICATION if order.account != None: notification = Notification() notification.account = order.account notification.content = notf notification.link = '/orders/' + order.order_id + '/' notification.save() return HttpResponseRedirect('/orders/management/')
def notifications(request): if request.method == 'POST': sender_user = request.user traveller_id = request.POST['traveller_id'] receiver = get_object_or_404(Traveller, pk=traveller_id) sender_name = sender_user.first_name + " " + sender_user.last_name receiver_user = get_object_or_404(User, email=receiver.email) reg_date = datetime.datetime.utcnow().replace(tzinfo=utc) #Check if user has made request already if request.user.is_authenticated: current_user = request.user has_requested = Notification.objects.all().filter( receiver_email=receiver_user, sender_email=sender_user, completed=False) if has_requested: messages.error(request, 'You have already made a request to this guide') return redirect('/view_profile/' + traveller_id) else: notification = Notification(receiver_email=receiver_user, sender_email=sender_user, sender_name=sender_name, reg_date=reg_date) notification.save() return redirect('/view_profile/' + traveller_id) return redirect('/view_profile/' + traveller_id)
def user_comment_post(sender, instance, *args, **kwargs): comment = instance post = comment.post text_preview = comment.body[:90] sender = comment.user notify = Notification(post=post, sender=sender, user=post.user, text_preview=text_preview, notification_type=2) notify.save()
def reactionLove(request, id): if not request.user.is_authenticated(): raise Http404 print("this should work !") product = get_object_or_404(Product, id=id) oldReaction = Reaction.objects.filter(user=request.user, product=product) for old in oldReaction: old.delete() reaction = Reaction(user=request.user, product=product, reaction_type='love') reaction.save() if request.user.id != product.table.user.id: notif = Notification(from_user=request.user, to_user=product.table.user, notification_type='love', product=product) notif.save() ret = Reaction.objects.filter(product=product).count() print( "reaction --Love-- added successfully from reactions application...") return HttpResponse(ret)
def done(request,id): if not request.user.is_authenticated: return redirect('login') profile= Profile.objects.get(user=request.user) if not profile.isTeacher: return redirect('profile') try: session = Session.objects.get(id=id) except Session.DoesNotExist: messages.add_message(request,messages.ERROR, "Session does not exist!") return redirect('profile') if not session.teacher==profile.Teacher: messages.add_message(request,messages.ERROR, "Thats not your session!") return redirect('profile') session.done=True session.changedForStudent=True session.changedForTeacher=True session.save() n=Notification( title='Pending Changes In Session', text=profile.getName()+ ' has marked a session as done. This means you can now provide feedback and review your progress. Please mark the session complete once you are done.', target=session.student.profile, link="/school/session/"+str(id), css="warning" ) n.save() messages.add_message(request, messages.SUCCESS, "Session done!") return redirect('profile')
def get(self, request, format=None, pk=None): following_user = request.user to_be_followed_user = get_object_or_404(models.User, pk=pk) # Create a notification for the post owner if not following_user in to_be_followed_user.followers.all(): notifications = Notification.objects.filter(user_tx=following_user) notified = False for notification in notifications: if notification.user_rx == to_be_followed_user and notification._type == 'follow': notified = True if not notified: # Create notification if ine hasn't been made already notification = Notification() notification._type = 'follow' # I am using rx to mean receiver and tx to mean transceiver notification.user_rx = to_be_followed_user notification.user_tx = following_user notification.save() if following_user.is_authenticated: if following_user in to_be_followed_user.followers.all(): to_be_followed_user.followers.remove(following_user) following_user.following.remove(to_be_followed_user) following = False else: to_be_followed_user.followers.add(following_user) following_user.following.add(to_be_followed_user) following = True updated = True data = {'following': following, 'updated': updated} return Response(data)
def requestreview(request,id): if not request.user.is_authenticated: return redirect('login') profile= Profile.objects.get(user=request.user) if not profile.isParent: return redirect('profile') try: session = Session.objects.get(id=id) except Session.DoesNotExist: messages.add_message(request,messages.ERROR, "Session does not exist!") return redirect('profile') if not session.student.parent==profile: messages.add_message(request,messages.ERROR, "Thats not your session!") return redirect('profile') if (not session.done) or session.completed or session.paid: messages.add_message(request,messages.ERROR, "Session needs to be unpaid, done and uncompleted!") return redirect('/school/session/'+id) session.changedForTeacher=True n=Notification( title='Review Session Request', text=profile.getName()+ ' has requested a session review. This means the parent believes the session has been paid for.'+ ' Please check for an income of £'+str(session.cost)+' for the session on '+session.date.strftime("%d/%m/%Y at %H:%M")+ ".\n\nPayment Reference: "+session.getReference(), target=session.teacher.profile, link="/school/session/"+id, css="warning" ) n.save() messages.add_message(request,messages.SUCCESS, "Review request completed. The teacher will receive an email and a notification prompting them to check for the payment.") return redirect('/school/session/'+id)
def _notify_users(self, level, verb, threshold): """ creates notifications for users """ opts = dict(actor=self, level=level, verb=verb, action_object=threshold) if self.content_object is None: opts['actor'] = self target_org = None else: opts['target'] = self.content_object target_org = getattr(opts['target'], 'organization_id', None) self._set_extra_notification_opts(opts) # retrieve superusers where = Q(is_superuser=True) # if target_org is specified, retrieve also # staff users that are member of the org if target_org: where = (where | (Q(is_staff=True) & Q(openwisp_users_organization=target_org))) # only retrieve users which have the receive flag active where = where & Q(notificationuser__receive=True) # perform query qs = User.objects.select_related('notificationuser') \ .order_by('date_joined') \ .filter(where) for user in qs: n = Notification(**opts) n.recipient = user n.full_clean() n.save()
def topic(request,id): if not request.user.is_authenticated: return redirect('login') profile=Profile.objects.get(user=request.user) try: topic = Topic.objects.get(id=id) except Topic.DoesNotExist: messages.add_message(request,messages.ERROR, "Session does not exist!") return redirect('profile') resources = topic.Resources.filter(approved=True) template="viewtopic.html" context={"resources":resources, "topic":topic} if request.method=="POST": resource=Resource() form=AddResourceForm(request.POST, instance=resource) if form.is_valid(): resource=form.save() resource.approved = profile.isTeacher resource.save() messages.add_message(request,messages.SUCCESS, "Resource added to topic(s)!") n=Notification( title="New Resource", text=profile.getName() + " has added a resource. Please review it.", target=Profile.objects.get(isTeacher=True, user__is_superuser=True), link="/school/topic/"+str(id), css="warning" ) n.save() else: form=AddResourceForm() context.update({"form":form}) return render(request,template,context)
def create(self, validated_data): note = Note.objects.create(**validated_data) action_type = 'NOTE ADDED' # contentType = ContentType.objects.get(pk=note.content_type.id) if note.object_type == 'Document': document = Document.objects.get(pk = note.object_id) noteFor = note.object_type + ' ' + document.name slug = slugify(document.subProcess.name) link = slug message = 'Added note for ' + noteFor contentType = ContentType.objects.get(model='document') notification = Notification(message=message,content_type=contentType,object_id=note.object_id,link=link,committee=note.committee,action_type=action_type) notification.save() return note