def get_context_data(self, **kwargs): context = super(Home, self).get_context_data(**kwargs) now = datetime.now() context['games'] = Schedule.objects.filter( match_date__gt=now).order_by('match_date') context['last'] = Schedule.objects.filter( match_date__lte=now).order_by('-match_date') # All Sports context['sport_list'] = Sports.objects.filter( is_current=True).order_by('-sport_name') # Activity Feed stream_one = model_stream(Photo) stream_two = model_stream(Schedule) stream_three = model_stream(GameNotes) context['stream'] = stream_one | stream_two | stream_three # Get profile for an authenticated user # NO, it's not DRY but the inclusion tag isn't working. Eat butt if self.request.user.is_authenticated: my_profile = Profile.objects.get(user=self.request.user) or None if my_profile: q = my_profile.team context['game'] = Schedule.objects.filter( Q(home=q) | Q(away=q)).filter(match_date__year=now.year).filter( match_date__month=now.month).filter( match_date__day=now.day) else: pass return context
def home(request): date = datetime.datetime.today() - datetime.timedelta(days=30) documents = Document.objects.all().count() reports = Report.objects.all().count() orders = Order.objects.all().count() parts = Part.objects.all().count() log = model_stream(request.user)[:8] news = NewsItem.objects.all().order_by('-date')[:5] data = Report.objects.filter(created_at__gte=date) r_graph = graph_utils.flot_values(data) data = Document.objects.filter(created_at__gte=date) d_graph = graph_utils.flot_values(data) data = Order.objects.filter(created_at__gte=date) o_graph = graph_utils.flot_values(data) data = Part.objects.filter(created_at__gte=date) p_graph = graph_utils.flot_values(data) return render_to_response('dashboard/home.html', { 'doc_count': documents, 'report_count': reports, 'order_count': orders, 'part_count': parts, 'log': log, 'news': news, 'report_graph': r_graph, 'document_graph': d_graph, 'order_graph': o_graph, 'part_graph': p_graph, }, context_instance=RequestContext(request))
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) response_files = ResponseFile.objects \ .filter(question__theme__questionnaire=self.get_object()) \ .filter(is_deleted=True) response_file_ids = response_files.values_list('id', flat=True) stream = model_stream(ResponseFile)\ .filter(verb='trashed response-file')\ .filter(target_object_id__in=list(response_file_ids)) \ .order_by('timestamp') response_file_list = [] for action in stream: response_file = response_files.get(id=action.target_object_id) response_file.deletion_date = action.timestamp response_file.deletion_user = User.objects.get( id=action.actor_object_id) response_file.question_number = str(response_file.question.theme.numbering) + \ '.' + str(response_file.question.numbering) response_file_list.append(response_file) response_file_list.sort(key=lambda x: x.question_number) context['response_file_list'] = response_file_list return context
def include_activity_stream(request): return {} if request.user.is_authenticated(): activity_stream = model_stream(request.user) return {'activitystream': activity_stream } else: return {}
def get_user_stream(user): """ Return a list of recent activities of interest for normal users. """ spaces = get_accessible_spaces(user) ret = model_stream(Space, target_object_id__in=spaces)[:10] return ret
def get_context_data(self, *args, **kwargs): context = super(ProjectRecentChangesView, self).get_context_data(**kwargs) # limiting to actions less then 1 month old threshold = datetime.now() - timedelta(days=30) context["activity"] = model_stream(I4pProject).filter(timestamp__gte=threshold) return context
def test_model_actions_with_kwargs(self): """ Testing the model_actions method of the ActionManager by passing kwargs """ self.assertEqual(map(unicode, model_stream(self.user1, verb='commented on')), [ u'admin commented on CoolGroup 0 minutes ago', ])
def author_id(self): stream = model_stream(Questionnaire) creation_action = stream.filter(action_object_object_id=self.id)\ .filter(verb='created questionnaire')\ .first() if creation_action is None: return None return creation_action.actor_object_id
def test_model_actions_with_kwargs(self): """ Testing the model_actions method of the ActionManager by passing kwargs """ self.assertSetEqual(model_stream(self.user1, verb='commented on'), [ 'admin commented on CoolGroup %s ago' % self.timesince, ])
def test_item_reopened_signal(self): self.client.login(username=self.lawyer.username, password=self.password) resp = self.client.patch(self.endpoint, json.dumps({'is_complete': 'true'}), content_type='application/json') self.assertEqual(resp.status_code, 200) stream = model_stream(Item) self.assertEqual(len(stream), 2) # shall only find the newest entry, the 2 other ones are too old. self.assertEqual(stream[0].data['override_message'], u'Lawyër Tëst closed Item Data Test No. 1') resp = self.client.patch(self.endpoint, json.dumps({'is_complete': 'false'}), content_type='application/json') self.assertEqual(resp.status_code, 200) stream = model_stream(Item) self.assertEqual(len(stream), 3) self.assertEqual(stream[0].data['override_message'], 'Lawyër Tëst reopened Item Data Test No. 1')
def test_model(self): response = self.get('actstream_model', self.user_ct.pk) self.assertTemplateUsed(response, 'actstream/actor.html') self.assertTemplateUsed(response, 'base.html') self.assertEqual(response.context['ctype'], self.user_ct) self.assertEqual(response.context['actor'], self.user_ct.model_class()) self.assertQSEqual(response.context['action_list'], models.model_stream(self.user1))
def get_context_data(self, *args, **kwargs): context = super(ProjectRecentChangesView, self).get_context_data(**kwargs) # limiting to actions less then 1 month old threshold = datetime.now() - timedelta(days=30) context['activity'] = model_stream(I4pProject).filter( timestamp__gte=threshold) return context
def model(request, content_type_id): """ ``Actor`` focused activity stream for actor defined by ``content_type_id``, ``object_id`` """ ctype = get_object_or_404(ContentType, pk=content_type_id) actor = ctype.model_class() return render_to_response('activity/actor.html', { 'action_list': model_stream(actor),'ctype':ctype,'actor':ctype#._meta.verbose_name_plural.title() }, context_instance=RequestContext(request))
def inner(self): self._the_zombies_are_coming({'human': 10, 'zombie': 1}) ci = len(connection.queries) length, limit = f(self) result = list([map(unicode, (x.actor, x.target, x.action_object)) for x in model_stream(User, _limit=limit)]) self.assert_(len(connection.queries) - ci <= 4, 'Too many queries,' ' got %d expected no more than 4' % len(connection.queries)) self.assertEqual(len(result), length) return result
def test_change_name_signal(self): self.client.login(username=self.lawyer.username, password=self.password) resp = self.client.patch(self.endpoint, json.dumps({'name': 'New Name'}), content_type='application/json') self.assertEqual(resp.status_code, 200) stream = model_stream(Item) self.assertEqual(len(stream), 2) self.assertEqual(stream[0].data['override_message'], u'Lawyër Tëst renamed Item Data Test No. 1 to New Name')
def model(request, content_type_id): """ ``Actor`` focused activity stream for actor defined by ``content_type_id``, ``object_id``. """ ctype = get_object_or_404(ContentType, pk=content_type_id) model_class = ctype.model_class() return render(request, 'actstream/actor.html', context={ 'action_list': models.model_stream(model_class), 'ctype': ctype, 'actor': model_class })
def model(request, content_type_id): """ ``Actor`` focused activity stream for actor defined by ``content_type_id``, ``object_id``. """ ctype = get_object_or_404(ContentType, pk=content_type_id) actor = ctype.model_class() return render_to_response(('actstream/actor.html', 'activity/actor.html'), { 'action_list': models.model_stream(actor), 'ctype': ctype, 'actor': actor }, context_instance=RequestContext(request))
def model(request, content_type_id): """ ``Actor`` focused activity stream for actor defined by ``content_type_id``, ``object_id``. """ ctype = get_object_or_404(ContentType, pk=content_type_id) actor = ctype.model_class() return render_to_response(('actstream/actor.html', 'activity/actor.html'), { 'action_list': models.model_stream(actor), 'ctype': ctype, 'actor': ctype }, context_instance=RequestContext(request))
def model(request, content_type_id): """ ``Actor`` focused activity stream for actor defined by ``content_type_id``, ``object_id``. """ ctype = get_object_or_404(ContentType, pk=content_type_id) model_class = ctype.model_class() return render_to_response( "actstream/actor.html", {"action_list": models.model_stream(model_class), "ctype": ctype, "actor": model_class}, context_instance=RequestContext(request), )
def model(request, content_type_id): """ ``Actor`` focused activity stream for actor defined by ``content_type_id``, ``object_id``. """ ctype = get_object_or_404(ContentType, pk=content_type_id) model_class = ctype.model_class() return render( request, 'actstream/actor.html', { 'action_list': models.model_stream(model_class), 'ctype': ctype, 'actor': model_class })
def model(request, content_type_id): """ ``Actor`` focused activity stream for actor defined by ``content_type_id``, ``object_id`` """ ctype = get_object_or_404(ContentType, pk=content_type_id) actor = ctype.model_class() return render_to_response( 'activity/actor.html', { 'action_list': model_stream(actor), 'ctype': ctype, 'actor': ctype #._meta.verbose_name_plural.title() }, context_instance=RequestContext(request))
def inner(self): self._the_zombies_are_coming({'human': 10, 'zombie': 1}) ci = len(connection.queries) length, limit = f(self) result = list([ map(unicode, (x.actor, x.target, x.action_object)) for x in model_stream(User, _limit=limit) ]) self.assert_( len(connection.queries) - ci <= 4, 'Too many queries, got %d expected no more than 4' % len(connection.queries)) self.assertEqual(len(result), length) return result
def get_queryset(self): if not self.request.user.profile.is_inspector: return Control.objects.none() questionnaires_in_control = Questionnaire.objects.filter( control__in=self.request.user.profile.controls.all()) authoring_actions = model_stream(Questionnaire)\ .filter(verb='created questionnaire')\ .filter(actor_object_id=self.request.user.id) authored_questionnaires_ids = authoring_actions.values_list( 'action_object_object_id', flat=True) return questionnaires_in_control.filter( id__in=list(authored_questionnaires_ids))
def get_context_data(self, **kwargs): # now().date is the way to go over datetime.now() now = datetime.now().date() context = super(SportView, self).get_context_data(**kwargs) q = self.kwargs.get('sport') context['sport'] = Teams.objects.filter(sport_id=q).order_by('-win') context['sport_name'] = Sports.objects.get(sport=q) context['upcoming'] = Schedule.objects.filter( Q(home__sport=q) | Q(away__sport=q)).filter(match_date__gte=now) context['recent'] = Schedule.objects.filter( Q(home__sport=q) | Q(away__sport=q)).filter(match_date__lte=now) # Activity Feed, sorting done in template context['stream'] = model_stream(Schedule) return context
def count_users_actions(self, user): """ Count actions related to this place performed by particular provided user. """ ct = ContentType.objects.get_for_model(User) pk = user.pk target_ct = ContentType.objects.get_for_model(self) stream = model_stream(self) actions = stream.filter(target_content_type=target_ct) actions = actions.filter(actor_content_type=ct) actions = actions.filter(actor_object_id=pk) actions = actions.filter(target_object_id=self.pk) return actions.count()
def index(request, template='index.html', extra_context=None): all_updates = model_stream(model=User) context = { 'all_updates': all_updates, } if request.user.is_authenticated: profile_updates = user_stream(request.user, with_user_activity=True) context['profile_updates'] = profile_updates if extra_context is not None: context.update(extra_context) return render(request, template, context)
def test_zombies(self): from random import choice, randint humans = [User.objects.create(username='******' % i) for i in range(10)] zombies = [User.objects.create(username='******' % j) for j in range(2)] while len(humans): for z in zombies: if not len(humans): break victim = choice(humans) humans.pop(humans.index(victim)) victim.save() zombies.append(victim) action.send(z,verb='killed',target=victim) self.assertEqual(map(unicode,model_stream(User))[:5], map(unicode,Action.objects.order_by('-timestamp')[:5]))
def test_zombies(self): from random import choice, randint humans = [User.objects.create(username="******" % i) for i in range(10)] zombies = [User.objects.create(username="******" % j) for j in range(2)] while len(humans): for z in zombies: if not len(humans): break victim = choice(humans) humans.pop(humans.index(victim)) victim.save() zombies.append(victim) action.send(z, verb="killed", target=victim) self.assertEqual(map(unicode, model_stream(User))[:5], map(unicode, Action.objects.order_by("-timestamp")[:5]))
def get_queryset(self, pk=None, ct=None): from actstream.models import Action, model_stream if not pk: return [] content_type = ContentType.objects.get_for_model(Location).pk stream = model_stream(Location).filter(target_content_type_id=content_type) try: location = Location.objects.get(pk=pk) stream = stream.filter(target_object_id=location.pk) ctid = ContentType.objects.get_for_model(Idea).pk vote_actions = [a.pk for a in Action.objects.all() if \ hasattr(a.action_object, 'location') and \ a.action_object.location==location] stream = stream | Action.objects.filter(pk__in=vote_actions) except Location.DoesNotExist: return [] if ct: stream = stream.filter(action_object_content_type_id=ct) return stream
def test_zombies(self): from random import choice, randint humans = [Player.objects.create() for i in range(10)] zombies = [Player.objects.create(state=1) for _ in range(2)] while len(humans): for z in zombies: if not len(humans): break victim = choice(humans) humans.pop(humans.index(victim)) victim.state = 1 victim.save() zombies.append(victim) action.send(z,verb='killed',target=victim) self.assertEqual(map(unicode,model_stream(Player))[:5], map(unicode,Action.objects.order_by('-timestamp')[:5]))
def context_feed(context_name, user=None): """ Stream of most recent actions by any particular model and filter it by its context attribute """ ret = ActionModel.objects.none() if user: # node events ret = model_stream(NodeHandle) # filter by context and readable ids readable_ids = sriutils.get_ids_user_canread(user) ret = ret.filter(Q(data__contains={'context_name': context_name}), Q(action_object_object_id__in=readable_ids)) # add delete events del_qs = ActionModel.objects.filter( Q(data__contains={'context_name': context_name}), Q(public=True), Q(verb="delete")) ret = (ret | del_qs).distinct() return ret
def items(self): return model_stream(I4pProject)[:100]
def show_model_stream(context, model, offset=0, count=30): params = {"actions": model_stream(model)[offset:count]} context.update(params) return context
def get_context_data(self, **kwargs): context = super(NewsfeedView, self).get_context_data(**kwargs) stream = model_stream(Process) context['process_stream'] = stream[:20] context['my_process_stream'] = [x for x in stream if x.actor == self.request.user][:20] return context
def test_query_count_sliced(self): queryset = model_stream(self.User)[:5] result = self.check_query_count(queryset) self.assertEqual(len(result), 5)
def test_query_count(self): queryset = model_stream(self.User) result = self.check_query_count(queryset) self.assertEqual(len(result), 10)
def test_query_count_sliced(self): queryset = model_stream(User)[:5] result = self.check_query_count(queryset) self.assertEqual(len(result), 5)
def get_object_list(self, request): return model_stream(request.user)
def home(request): return render(request, "index.html", {'activities': model_stream(get_user_model())[:10] })
def get_queryset(self): return model_stream(self.model).filter(target_object_id=self.matter.pk)
def test_query_count(self): User = get_user_model() queryset = model_stream(User) result = self.check_query_count(queryset) self.assertEqual(len(result), 10)
def items(self, model): i = model_stream(model) if i: return i[:30] return []
def test_query_count(self): queryset = model_stream(User) result = self.check_query_count(queryset) self.assertEqual(len(result), 10)