def post(self, request): data = json.loads(request.body.decode()) activityName = data['activityName'] if activityName == '': return sendError(message='Tienes que agregar una actividad') if len(activityName) > 100: return sendError(message='El nombre del curso es demasiado grande') if 'activityDesc' in data: activityDesc = data['activityDesc'] else: activityDesc = '' newActivity = Activity(name=activityName, teacher=request.user.teacher, description=activityDesc) newActivity.save() data = {'id': newActivity.id, 'name': newActivity.name} return sendResponse(data=data, message='Actividad {} agregada'.format( data['name']), code=201)
def submit(request): if request.POST["name"]=="": return HttpResponseRedirect(reverse('activities:index')) else: ac = Activity(name = request.POST["name"],type = request.POST["type"],date = request.POST["date"],description = request.POST["description"],pub_date = timezone.now() ) ac.save() return HttpResponseRedirect(reverse('activities:list'))
def index(request): results = {} today = timezone.now() if request.user.is_staff: yesterday = today - datetime.timedelta(days=1) results['yesterday'] = Activity.objects.filter(activity_date=yesterday.date()) results['today'] = Activity.objects.filter(activity_date=today) context = {'results': results, 'yesterday' : yesterday, 'today': today} return render(request, 'activities/admin_dashboard.html', context) else: results['all'] = Activity.objects.filter(author__username=request.user.username) results['today'] = [item for item in results['all'] if item.activity_date == today.date()] results['last_seven_days'] = [item for item in results['all'] \ if (item.activity_date + datetime.timedelta(days=7) > today.date() \ and item.activity_date < today.date())] if request.method == "POST": form = ActivityForm(request.POST) if form.is_valid(): activity = Activity(author=request.user, description=form.cleaned_data["description"], activity_date=form.cleaned_data["activity_date"], activity_type=form.cleaned_data["activity_type"], ticket_number=form.cleaned_data["ticket_number"], hours_worked=form.cleaned_data["hours_worked"], comment=form.cleaned_data["comment"]) activity.save() messages.add_message(request, messages.SUCCESS, "Activity added successfully!") return redirect(reverse('index')) else: form = ActivityForm() context = { 'name' : request.user.username, 'results' : results, 'form' : form , 'today': today.date()} return render(request, "activities/dashboard.html", context)
def alter(self, instance, activity, **kwargs): # 状態が draft の場合は通知しない if activity and instance.pub_state == 'draft': return None if activity and activity.status == 'updated': if activity.previous: # 通知が必要な状態の変更を詳細に記録する previous = activity.previous.snapshot is_created = lambda x: (not getattr(previous, x) and getattr( instance, x)) is_updated = lambda x: (getattr(previous, x) and getattr( instance, x) and getattr(previous, x) != getattr( instance, x)) is_deleted = lambda x: (getattr(previous, x) and not getattr( instance, x)) remarks = [] attributes = ( 'title', 'body', 'icon', 'status', 'category', ) for attribute in attributes: if is_created(attribute): remarks.append(attribute + '_created') elif is_updated(attribute): remarks.append(attribute + '_updated') elif is_deleted(attribute): remarks.append(attribute + '_deleted') if not remarks: # 通知が必要な変更ではないため通知しない return None activity.remarks = "\n".join(remarks) elif activity is None: # m2m_updated action = kwargs.get('action') model = kwargs.get('model') if action not in ('post_add', 'post_remove'): # 追加/削除以外は通知しない return None if action == 'post_add' and instance.members.count() == 1: # models.join_administratorシグナルによりpost_save処理より以前に # 作成者参加が行われ project が作成される前に参加者が追加される # したがって参加者が一人(join_administratorにより追加された直後) # の場合に飛んできた m2m_signal は無視 return None # 追加・削除をトラックするActivityを作成 ct = ContentType.objects.get_for_model(instance) status = 'user_added' if action == 'post_add' else 'user_removed' activity = Activity(content_type=ct, object_id=instance.pk, status=status) # snapshot を保存 activity.snapshot = instance # 追加・削除されたユーザーのIDを保存 activity.remarks = " ".join(map(str, kwargs.get('pk_set'))) return activity
def test_saving_and_retrieving_activity(self): new_activity = Activity() new_activity.text = 'The new activity' new_activity.save() saved_activity = Activity.objects.all() self.assertEqual(saved_activity.count(), 1) only_activity = saved_activity[0] self.assertEqual(only_activity.text, 'The new activity')
def add(request): name = request.POST.get('name','') img = request.FILES.get('image','') order = len(Activity.objects.all()) img.name = name + '.' + img.name.split('.')[-1] activity = Activity(name=name,order=order,img=img) activity.save() return HttpResponseRedirect('/activities/edit/')
def update(self, instance: Activity, validated_data): if 'presenter' in validated_data: presenter_data = validated_data.pop('presenter') instance.presenter.clear() for presenter in presenter_data: u = User.objects.get(id=presenter['id']) instance.presenter.add(u) instance = super().update(instance, validated_data) # 更新 title 等数据 instance.save() return instance
def vote(request): answer_id = request.POST['answer'] answer = Answer.objects.get(pk=answer_id) vote = request.POST['vote'] user = request.user activity = Activity.objects.filter(Q(activity_type=Activity.UP_VOTE) | Q(activity_type=Activity.DOWN_VOTE), user=user, answer=answer_id) if activity: activity.delete() if vote in [Activity.UP_VOTE, Activity.DOWN_VOTE]: activity = Activity(activity_type=vote, user=user, answer=answer_id) activity.save() return HttpResponse(answer.calculate_votes())
def favorite(request): question_id = request.POST['question'] question = Question.objects.get(pk=question_id) user = request.user activity = Activity.objects.filter(activity_type=Activity.FAVORITE, user=user, question=question_id) if activity: activity.delete() user.profile.unotify_favorited(question) else: activity = Activity(activity_type=Activity.FAVORITE, user=user, question=question_id) activity.save() user.profile.notify_favorited(question) return HttpResponse(question.calculate_favorites())
def like(request): feed_id = request.POST['feed'] feed = Feed.objects.get(pk=feed_id) user = request.user like = Activity.objects.filter(activity_type=Activity.LIKE, feed=feed_id, user=user) if like: user.profile.unotify_liked(feed) like.delete() else: like = Activity(activity_type=Activity.LIKE, feed=feed_id, user=user) like.save() user.profile.notify_liked(feed) return HttpResponse(feed.calculate_likes())
def like(request): feed_id = request.POST["feed"] feed = Feed.objects.get(pk=feed_id) user = request.user like = Activity.objects.filter(activity_type=Activity.LIKE, feed=feed_id, user=user) if like: user.profile.unotify_liked(feed) like.delete() else: like = Activity(activity_type=Activity.LIKE, feed=feed_id, user=user) like.save() user.profile.notify_liked(feed) return HttpResponse(feed.calculate_likes())
def save(self, user): """Calculates average values and saves the data into the database. Arguments: user: user who uploaded the file """ data = self.cleaned_data data['speed_avg'] = data['total_distance'] / data['elapsed'] * 360 activity = Activity(user=user, **data) activity.save() return activity.id
def post(self, request): form = self.form(request.POST) if form.is_valid(): try: user_id = request.session.get('userauth', {}).get('user_id') task_name = request.POST.get('name') data = { 'name': task_name, 'deadline': request.POST.get('deadline_date'), 'user_id': user_id } task_obj = Task(**data) task_obj.save() # update activity activity_dict = { 'user_id': user_id, 'message': 'You created Task, {}'.format(str(task_name)) } Activity(**activity_dict).save() messages.success(request, "Task add successfully !") return redirect('task-list') except RuntimeWarning: return redirect('task-list') return render(request, self.template_name, {'form': form})
def follow(request): try: user_id = request.GET['user-id'] to_user = get_object_or_404(User, pk=user_id) from_user = request.user following = from_user.profile.get_following() if to_user not in following: activity = Activity(from_user=from_user, to_user=to_user, activity_type=Activity.FOLLOW) activity.save() return HttpResponse() else: return HttpResponseBadRequest() except: return HttpResponseBadRequest()
def new_post(request): #post with images and require page refresh user = request.user form = FeedForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = user is_challenge = request.POST.get('is_challenge') #need to set a post whether its a challenge post or not is_response = request.POST.get('is_response') #need to set a post whether its a response post or not response_for_id = request.POST.get('response_for_id') #required to generate notification for the user for whome the challnege was originally to_user = request.POST.get('to_user') #comes in all response feeds and in challenges where to_user is not left blan as its optional if response_for_id: response_for_feed=get_object_or_404(Feed, id=response_for_id) response_for_user_indirect=response_for_feed.challenge_to_user if response_for_user_indirect: to_user_profile_pk_indirect=response_for_user_indirect.profile.pk to_user_profile_indirect=Profile.objects.get(pk=to_user_profile_pk_indirect) if to_user: to_user = get_object_or_404(User, username=to_user) to_user_profile_pk=to_user.profile.pk to_user_profile=Profile.objects.get(pk=to_user_profile_pk) post = request.POST['post'] post = post.strip() #+ str(to_user_profile_pk_indirect) if len(post) > 0: instance.post = post[:255] if is_response: instance.to_user = to_user instance.response_for = response_for_id if is_challenge: instance.is_challenge = is_challenge if to_user: instance.challenge_to_user = to_user instance.save() feed=instance # instance.optimize_image() if is_challenge == '1': if to_user: challengedActivity=Activity(activity_type=Activity.CHALLENGED, profile=to_user_profile_pk, user=user, ) challengedActivity.save() user.profile.notifyChallenged(to_user_profile,feed) # from user to to_user return redirect('challenge_feeds') elif is_response == '1': respondActivity=Activity(activity_type=Activity.RESPOND, profile=to_user_profile_pk, user=user) respondActivity.save() user.profile.notifyResponded(to_user_profile,feed) # if to_user_profile_pk_indirect: # respondIndirectActivity=Activity(activity_type=Activity.RESPOND_INDIRECT, profile=to_user_profile_pk_indirect, user=user) # respondIndirectActivity.save() # user.profile.notifyRespondedIndirect(to_user_profile_indirect,feed) return redirect('/feeds/response/%s'%(response_for_id)) return redirect('feeds')
def post_like(request): post_id = request.POST['post'] post = Post.objects.get(pk=post_id) user = request.user like = Activity.objects.filter(activity_type=Activity.LIKE, post=post_id, user=user) if like: user.profile.unotify_post_liked(post) like.delete() else: like = Activity(activity_type=Activity.LIKE, post=post_id, user=user) like.save() user.profile.notify_post_liked(post) return HttpResponse(post.calculate_likes())
def new_comment_signal(sender, instance=None, created=False, **kwargs): if created: post = instance.post user = instance.user post_owner = post.user if (post.is_paid() and user.is_vet() and post_owner.vet_reply_notification): send_notification_message(post_owner.id, vet_commenting_post) elif post_owner.comments_notification: send_notification_message(post_owner.id, commenting_post) activity = Activity(user=user, action=Activity.COMMENT, post=post, comment=instance) activity.save()
def like(request): #创建点赞和撤销点赞 article_id = request.POST['article'] article = Article.objects.get(pk=article_id) user = request.user like = Activity.objects.filter(activity_type=Activity.LIKE, article=article_id, user=user) #查询该用户是否点过赞 if like: #点过赞的撤销 user.profile.unotify_liked(article) like.delete() else: #没有点过赞的点赞 like = Activity(activity_type=Activity.LIKE, article=article_id, user=user) like.save() user.profile.notify_liked(article) return HttpResponse(str( article.calculate_likes())) #返回赞数,ajax用httpresponse,返回数据
def index(request): results = {} today = timezone.now() if request.user.is_staff: yesterday = today - datetime.timedelta(days=1) results['yesterday'] = Activity.objects.filter( activity_date=yesterday.date()) results['today'] = Activity.objects.filter(activity_date=today) context = {'results': results, 'yesterday': yesterday, 'today': today} return render(request, 'activities/admin_dashboard.html', context) else: results['all'] = Activity.objects.filter( author__username=request.user.username) results['today'] = [ item for item in results['all'] if item.activity_date == today.date() ] results['last_seven_days'] = [item for item in results['all'] \ if (item.activity_date + datetime.timedelta(days=7) > today.date() \ and item.activity_date < today.date())] if request.method == "POST": form = ActivityForm(request.POST) if form.is_valid(): activity = Activity( author=request.user, description=form.cleaned_data["description"], activity_date=form.cleaned_data["activity_date"], activity_type=form.cleaned_data["activity_type"], ticket_number=form.cleaned_data["ticket_number"], hours_worked=form.cleaned_data["hours_worked"], comment=form.cleaned_data["comment"]) activity.save() messages.add_message(request, messages.SUCCESS, "Activity added successfully!") return redirect(reverse('index')) else: form = ActivityForm() context = { 'name': request.user.username, 'results': results, 'form': form, 'today': today.date() } return render(request, "activities/dashboard.html", context)
def review_like(request): review_id = request.POST['review'] review = Review.objects.get(pk=review_id) user = request.user like = Activity.objects.filter(activity_type=Activity.LIKE, review=review_id, user=user) if like: user.profile.unotify_review_liked(review) like.delete() else: like = Activity(activity_type=Activity.LIKE, review=review_id, user=user) like.save() user.profile.notify_review_liked(review) return HttpResponse(review.calculate_likes())
def user_activities(request, page): # get all the user's projects activities = Activity.getActivitiesForUser(request.user) paginator = Paginator(activities, 10) page_obj = paginator.page(page) return render_to_response("activities/activity_list.html", { "activities": page_obj.object_list, "activities_page":page_obj, }, context_instance=RequestContext(request))
def question_vote(request): question_id = request.POST['question'] question = Question.objects.get(pk=question_id) vote = request.POST['vote'] user = request.user activity = Activity.objects.filter( Q(activity_type=Activity.UP_VOTE) | Q(activity_type=Activity.DOWN_VOTE), # noqa: E501 user=user, question=question_id) if activity: activity.delete() if vote in [Activity.UP_VOTE, Activity.DOWN_VOTE]: activity = Activity(activity_type=vote, user=user, question=question_id) activity.save() return HttpResponse(question.calculate_votes())
def post(request): #feeds on profiles to_user = request.POST.get('to_user') # profile_pk = request.POST.get('profile_pk') # last_feed = request.POST.get('last_feed') to_user = get_object_or_404(User, username=to_user) to_user_profile_pk = to_user.profile.pk user = request.user csrf_token = (csrf(request)['csrf_token']) feed = Feed() feed.user = user feed.to_user = to_user feed.profile_pk = to_user_profile_pk # if not to_user: # feed.profile_pk = profile_pk # else: # feed.profile_pk = to_user.profile.pk # profile_pk = to_user.profile.pk post = request.POST['post'] post = post.strip() if len(post) > 0 and to_user: feed.post = post[:255] feed.save() profile = Profile.objects.get(pk=to_user_profile_pk) # to_user_profile # wrote_on_profile = Activity.objects.filter(activity_type=Activity.WROTE_ON_PROFILE, profile=profile_pk, # user=user) wrote_on_profile = Activity(activity_type=Activity.WROTE_ON_PROFILE, profile=to_user_profile_pk, user=user) wrote_on_profile.save() user.profile.notify_wrote_on_profile(profile,feed) html = '' html = '{0}{1}'.format(html, render_to_string('feeds/partial_feed_profile.html', { 'feed': feed, 'user': request.user, 'csrf_token': csrf_token, })) else: html = '' return HttpResponse(html)
def user_activities(request, page): # get all the user's projects activities = Activity.getActivitiesForUser(request.user) paginator = Paginator(activities, 10) page_obj = paginator.page(page) return render_to_response("activities/activity_list.html", { "activities": page_obj.object_list, "activities_page": page_obj, }, context_instance=RequestContext(request))
def log(instance,message): #check instance of user _user_instance = None if self.user: if hasattr(instance,self.user): _user_obj = getattr(instance,self.user) if callable(_user_obj): _user_insanctace = _user_obj(instance) else: _user_instance = _user_obj if not _user_instance.__class__ == User: raise Exception("User must instance of django.contrib.models.User") _activityInstance = Activity(user= _user_instance, content_object=instance, text=message) _activityInstance.save()
def post(self, request, *args, **kwargs): user = request.user form = self.get_form() if form.is_valid(): vehicle_id = request.POST['vehicle'] form.save() vehicle = Vehicle.objects.get(pk=vehicle_id) activity = Activity.objects.filter(activity_type=Activity.BOOK, user=user, vehicle=vehicle_id) if activity: activity.delete() user.profile.unotify_booked(vehicle) else: activity = Activity(activity_type=Activity.BOOK, user=user, vehicle=vehicle_id) activity.save() user.profile.notify_booked(vehicle) return self.form_valid(form) else: return self.form_invalid(form)
def home(request): my_projects = [] member_projects = [] organizations = [] activities = [] next_page = False if request.user.is_authenticated(): organizations = Organization.getOrganizationsForUser(request.user) activities = Activity.getActivitiesForUser(request.user) assigned_stories = Story.getAssignedStories(request.user) paginator = Paginator(activities, 10) page_obj = paginator.page(1) activities = page_obj.object_list next_page = page_obj.has_next() memberships = ProjectMember.objects.filter(user=request.user) for membership in memberships: try: if (membership.project.creator_id == request.user.id): my_projects.append(membership.project) else: member_projects.append(membership.project) except: pass num_projects = len(member_projects) + len( filter(lambda p: p.organization == None, my_projects)) blank_state = True if (num_projects + len(organizations)) == 0 else False return render_to_response( "homepage.html", { "my_projects": my_projects, "my_organizations": organizations, "activities": activities, "activities_next_page": next_page, "assigned_stories": assigned_stories, "return_type": "queue", # for the queue mini stories "member_projects": member_projects, "num_projects": num_projects, "now": datetime.datetime.now(), "blank_state": blank_state }, context_instance=RequestContext(request)) else: return render_to_response("unauthenticated_homepage.html", context_instance=RequestContext(request))
def home(request): my_projects = [] member_projects = [] organizations = [] activities = [] next_page = False if request.user.is_authenticated(): organizations = Organization.getOrganizationsForUser(request.user) activities = Activity.getActivitiesForUser(request.user) assigned_stories = Story.getAssignedStories(request.user) paginator = Paginator(activities, 10) page_obj = paginator.page(1) activities = page_obj.object_list next_page = page_obj.has_next() memberships = ProjectMember.objects.filter(user=request.user) for membership in memberships: try: if membership.project.creator_id == request.user.id: my_projects.append(membership.project) else: member_projects.append(membership.project) except: pass num_projects = len(member_projects) + len(filter(lambda p: p.organization == None, my_projects)) blank_state = True if (num_projects + len(organizations)) == 0 else False return render_to_response( "homepage.html", { "my_projects": my_projects, "my_organizations": organizations, "activities": activities, "activities_next_page": next_page, "assigned_stories": assigned_stories, "return_type": "queue", # for the queue mini stories "member_projects": member_projects, "num_projects": num_projects, "now": datetime.datetime.now(), "blank_state": blank_state, }, context_instance=RequestContext(request), ) else: return render_to_response("unauthenticated_homepage.html", context_instance=RequestContext(request))
def user_activities(request, page): # get all the user's projects activities = Activity.getActivitiesForUser(request.user) paginator = Paginator(activities, 40) try: page_obj = paginator.page(page) except EmptyPage: # someone asked for a page that has no entries raise Http404 return render_to_response("activities/activity_list.html", { "activities": page_obj.object_list, "activities_page":page_obj, }, context_instance=RequestContext(request))
def profile_like(request): profile_pk = request.POST['profile_pk'] profile = Profile.objects.get(pk=profile_pk) user = request.user like = Activity.objects.filter(activity_type=Activity.LIKE_PROFILE, profile=profile_pk, user=user) if like: user.profile.unotify_liked_profile(profile) print('request user: %s had already liked this user so \ you are gonna be removed from the liker list of this user\ and It should appear Like text on button' %(request.user.username)) like.delete() else: like = Activity(activity_type=Activity.LIKE_PROFILE, profile=profile_pk, user=user) print('request user: %s had not liked this user so \ you are gonna be added in liker list of this user\ and It should appear UnLike on button' %(request.user.username)) like.save() user.profile.notify_liked_profile(profile) # from user to => profile wala_user return HttpResponse(profile.calculate_likes())
def booking(request): user = request.user form = BookingForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() vehicle = Vehicle.objects.get(pk=2) activity = Activity.objects.filter(activity_type=Activity.BOOK, user=user, vehicle=2) if activity: activity.delete() user.profile.unotify_booked(vehicle) else: activity = Activity(activity_type=Activity.BOOK, user=user, vehicle=2) activity.save() user.profile.notify_booked(vehicle) return redirect('/') else: return HttpResponse('Error') return render(request, 'booking_form.html', {'form':form} )
def user_activities(request, page): # get all the user's projects activities = Activity.getActivitiesForUser(request.user) paginator = Paginator(activities, 10) try: page_obj = paginator.page(page) except EmptyPage: # someone asked for a page that has no entries raise Http404 return render_to_response("activities/activity_list.html", { "activities": page_obj.object_list, "activities_page": page_obj, }, context_instance=RequestContext(request))
def pubsvn(github): u = users.objects.get(svn=github) if Group.objects.filter(name="Commit").exists(): g = Group.objects.get(name="Commit") else: Group(name="Commit").save() g = Group.objects.get(name="Commit") if Entity.objects.filter(name="Commit", group=g).exists(): en = Entity.objects.get(name="Commit") else: Entity(name="Commit", group=g).save() en = Entity.objects.get(name="Commit") r = svn.remote.RemoteClient('http://svn.apache.org/repos/asf/') entries = r.list() for filename in entries: r = svn.remote.RemoteClient('http://svn.apache.org/repos/asf/' + filename) if Project.objects.filter(name=filename).exists(): pr = Project.objects.get(name=filename) #UserParticipation(user=u, project=pr).save() else: p = Project(name=filename, description=filename) p.save() pr = Project.objects.get(name=filename) #UserParticipation(user=u, project=pr) e = r.list() for file in e: if file == "trunk/": a = svn.remote.RemoteClient('http://svn.apache.org/repos/asf/' + filename + "trunk") i = 0 for log in a.log_default(): if log[3] == github: if Measurement.objects.filter(value=log[2]).exists(): continue else: i=i+1 Activity(comments="SVN commit " + str(i) + " " + str(filename) +" " + str(github), entity=en).save() ac = Activity.objects.get(comments="SVN commit " + str(i) + " " + str(filename) +" " + str(github)) Measurement(activity=ac, type="char", name="Type", value="SVN Commit").save() Measurement(activity=ac, type='char', name="User", value=github).save() Measurement(activity=ac, type="char", name="Scommit_ID", value=log[2]).save() if log[1]: Measurement(activity=ac, type="char", name="Scommit_message", value=log[1]).save() else: Measurement(activity=ac, type="char", name="Scommit_message", value="Nothing").save() return HttpResponse("Done")
def get(self, request, task_id): user_id = request.session.get('userauth', {}).get('user_id') try: task_obj = Task.objects.get(id=task_id, user_id=user_id) task_name = task_obj.name task_obj.delete() messages.success(request, "Task Deleted successfully !") # update activity activity_dict = { 'user_id': user_id, 'message': 'You deleted Task, {}'.format(str(task_name)) } Activity(**activity_dict).save() except Exception as e: print(e) return redirect ('task-list')
def svna(github,urls): u = users.objects.get(svn=github) if Group.objects.filter(name="Commit").exists(): g = Group.objects.get(name="Commit") else: Group(name="Commit").save() g = Group.objects.get(name="Commit") if Entity.objects.filter(name="Commit", group=g).exists(): en = Entity.objects.get(name="Commit") else: Entity(name="Commit", group=g).save() en = Entity.objects.get(name="Commit") for url in urls.split(','): r = svn.remote.RemoteClient(url) info=r.info() if Project.objects.filter(name=info['entry_path']).exists(): pr = Project.objects.get(name=info['entry_path']) #UserParticipation(user=u, project=pr).save() else: p = Project(name=info['entry_path'], description=info['entry_path']) p.save() pr = Project.objects.get(name=info['entry_path']) #UserParticipation(user=u, project=pr) i=0 for log in r.log_default(): if log[3] == github: if Measurement.objects.filter(value=log[1]).exists(): continue else: i = i + 1 Activity(comments="SVN commit " + str(i) + " " + str(info['entry_path']) +" " + str(github), entity=en).save() ac = Activity.objects.get(comments="SVN commit " + str(i) + " " + str(info['entry_path']) +" " + str(github)) Measurement(activity=ac, type="char", name="Type", value="SVN Commit").save() Measurement(activity=ac, type='char', name="User", value=github).save() Measurement(activity=ac, type="char", name="Scommit_ID", value=log[2]).save() if log[1]: Measurement(activity=ac, type="char", name="Scommit_message", value=log[1]).save() else: Measurement(activity=ac, type="char", name="Scommit_message", value="Nothing").save() return HttpResponse("Done")
def create_view(request): if not request.user.can_create_vote: return redirect('/activities/list/') if request.POST: activity = Activity() activity.title = request.POST.get('title', '') activity.vote_num_per_user = request.POST.get('vote_num_per_user', 8) activity.sponsor = request.user activity.end_datetime = request.POST.get('end_datetime', None) activity.save() images = request.FILES.getlist('option_image', []) contents = request.POST.getlist('option_content', []) for image, content in zip(images, contents): option = Option() option.image = image option.content = content option.activity = activity option.save() return redirect('/activities/detail/%s/' % activity.id) else: return render(request, 'activities/create.html')
def project_add_activity(request, pk): project = get_object_or_404(models.Project, pk=pk) activity = Activity(project=project) if in_list(project.status, '6,7,8'): messages.error(request, 'Projeto já Em Andamento / Encerrado / Cancelado.') return redirect(reverse('project:detail', kwargs={'pk': project.pk})) if not has_group(request.user, 'project_leader') or project.leader != request.user: messages.error( request, 'Apenas o Lider do Projeto pode adicionar ima atividade ao projeto.' ) return redirect(reverse('project:detail', kwargs={'pk': project.pk})) if request.method == 'POST': form = forms.NewProjectActivityForm(request.POST, instance=activity) if form.is_valid(): form.save() project.status = 1 project.save() messages.success(request, 'Atividade cadastrada com sucesso.') else: messages.error(request, 'Falha ao cadastrar a atividade do projeto.') return render(request, 'projects/project_add_activity.html', {'form': form}) return redirect(reverse('project:detail', kwargs={'pk': project.pk})) else: form = forms.NewProjectActivityForm(instance=activity) return render(request, 'projects/project_add_activity.html', {'form': form})
def fetchStrava(code, request): if request.user == '' or request.user == None: request.user = '******' access_token = getAccessToken(code) activites_url = "https://www.strava.com/api/v3/athlete/activities" header = {'Authorization': 'Bearer ' + access_token} print("Fill database") i = 1 while True: param = {'per_page': 200, 'page': i} current_activities = Activity.objects.filter(user=request.user) current_ids = set([i.strava_id for i in current_activities]) print(len(current_activities)) print(len(current_ids)) strava_activities = requests.get(activites_url, headers=header, params=param).json() print("current batch - " + str(len(strava_activities))) if len(strava_activities) == 0: break i += 1 for strava_activity in strava_activities: if strava_activity["id"] not in current_ids: activity = Activity() activity.strava_id = strava_activity["id"] activity.user = request.user activity.title = strava_activity["name"] activity.activity_type = strava_activity["type"] activity.date = datetime.strptime( strava_activity['start_date'][2:10], '%y-%m-%d') activity.timestamp = datetime.timestamp(activity.date) if strava_activity['has_heartrate']: activity.heartrate = strava_activity['average_heartrate'] if 'suffer_score' in strava_activity: activity.suffer = strava_activity['suffer_score'] else: activity.suffer = 0 else: activity.heartrate = 0 activity.suffer = 0 activity.distance = strava_activity['distance'] / 1000 activity.moving_time = strava_activity['elapsed_time'] activity.elevation = strava_activity['total_elevation_gain'] activity.speed = strava_activity['average_speed'] if activity.activity_type == "Run" or activity.activity_type == "Ride": if strava_activity['workout_type'] == None: activity.workout_type = 'niks' else: activity.workout_type = strava_activity['workout_type'] activity.save()
def serialize(self, o, **kwargs): if not isinstance(o, Track): raise TypeError('Object should be of type {}, is {}'.format(type(Track), type(o))) a = Activity() a.date = o.created_at a.elapsed = o.elapsed_time() a.moving = o.moving_time() a.total_distance = o.total_distance() a.elevation_gain = o.elevation_gain() a.speed_avg = o.average_speed() a.speed_max = o.max_speed() a.hr_avg = o.average_heart_rate() a.hr_max = o.max_heart_rate() a.zones_elevation = o.elevation_zones() a.zones_speed = o.speed_zones() a.zones_hr = o.heart_rate_zones() a.zones_grade = o.grade_zones() a.track = LineString(o.track()) a.time = o.time_entries() a.distance = o.distance_entries() hr = o.heart_rate_entries() a.heart_rate = [e if e else -1 for e in hr] if hr else None cad = o.cadence_entries() a.cadence = [e if e else -1 for e in cad] if cad else None temp = o.temperature_entries() a.temperature = [e if e else -1 for e in temp] if temp else None # User, activity type, objectives, etc. for key, value in kwargs.iteritems(): if key not in ['user', 'sport', 'description', 'comments', 'equipment', 'primary_objective', 'secondary_objective', 'rating']: continue setattr(a, key, value) return a
def obj_get_list(self, request=None, **kwargs): """ overriding """ return Activity.getActivitiesForUser(request.user)
def alter(self, instance, activity, **kwargs): # 状態が draft の場合は通知しない if activity and instance.pub_state == 'draft': return None if activity and activity.status == 'updated': # 通知が必要な状態の変更を詳細に記録する if activity.previous: previous = activity.previous.snapshot is_created = lambda x: ( not getattr(previous, x) and getattr(instance, x) ) is_updated = lambda x: ( getattr(previous, x) and getattr(instance, x) and getattr(previous, x) != getattr(instance, x) ) is_deleted = lambda x: ( getattr(previous, x) and not getattr(instance, x) ) remarks = [] attributes = ( 'period_start', 'period_end', 'place', 'category', 'number_restriction', 'attendance_deadline', ) for attribute in attributes: if is_created(attribute): remarks.append(attribute + '_created') elif is_updated(attribute): remarks.append(attribute + '_updated') elif is_deleted(attribute): remarks.append(attribute + '_deleted') if not remarks: # 通知が必要な変更ではないため通知しない return None activity.remarks = "\n".join(remarks) elif activity is None: # m2m_updated action = kwargs.get('action') model = kwargs.get('model') if action not in ('post_add', 'post_remove'): # 追加/削除以外は通知しない return None if action == 'post_add' and instance.attendees.count() == 1: # models.join_organizerシグナルによりpost_save処理より以前に # 作成者参加が行われ event が作成される前に参加者が追加される # したがって参加者が一人(join_organizerにより追加された直後) # の場合に飛んできた m2m_signal は無視 return None # 追加・削除をトラックするActivityを作成 ct = ContentType.objects.get_for_model(instance) status = 'user_added' if action == 'post_add' else 'user_removed' activity = Activity(content_type=ct, object_id=instance.pk, status=status) # 追加・削除されたユーザーのIDを保存 activity.remarks = " ".join(map(str, kwargs.get('pk_set'))) return activity
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.views.generic import TemplateView, RedirectView from smartpages.views import SmartPageView from django.contrib import admin from django.contrib.sitemaps.views import sitemap from smartpages.models import SmartPage from activities.models import Activity, Collection # import markupmirror.urls sitemaps = { 'smartpages': SmartPage.sitemap(), 'activities': Activity.sitemap(priority=0.7), 'collections': Collection.sitemap(priority=0.6), } urlpatterns = i18n_patterns( url(r'^$', 'astroedu.views.home', name='home'), url(r'^search/', 'astroedu.search.views.search', name='search'), url(r'^testing/', include('astroedu.testing.urls', namespace='testing')), url(r'^activities/', include('activities.urls', namespace='activities')), url(r'^collections/', include('activities.urls_collections', namespace='collections')), # (r'^markupmirror/', include(markupmirror.urls.preview)), # url('^markdown/', include( 'django_markdown.urls')), # url(r'^grappelli/', include('grappelli.urls')), # url(r'^tinymce/', include('tinymce.urls')),
def GenerateTestData(events, actions): mindate = datetime.datetime(2012, 01, 01) startdiffusion = 180 maxdate = datetime.datetime(2012, 12, 31) enddiffusion = 180 stcmindiff = 12 stcdiff = 20 for enr in range(events): dt = mindate + datetime.timedelta(random.randint(0, startdiffusion)) deleted = random.randint(0, 4) == 0 evt = Event() evt.start_date = dt evt.start_time = datetime.time(0, 0, 0) evt.end_date = maxdate - datetime.timedelta(random.randint(0, enddiffusion)) evt.end_time = datetime.time(23, 59, 59) evt.deleted = deleted evt.pub_date = dt + datetime.timedelta(random.randint(-7, 7)) evt.status = random.randint(0, 3) evt.save() act1 = Activity() # act1.user = "******" act1.verb = VERB_CHANGED + " 3" act1.target_content_type_id = 9 # "event" act1.target_object_id = evt.pk act1.timestamp = dt act1.save() for actnr in range(actions): dt = dt + datetime.timedelta(random.randint(stcmindiff, stcmindiff + stcdiff)) act = Activity() # act.user = "******" if actnr + 1 == actions and deleted: act.verb = VERB_DELETED act.subject_content_type_id = 9 # "event" act.subject_object_id = evt.pk else: act.verb = "%s %d" % (VERB_CHANGED, random.randint(0, 3)) act.target_content_type_id = 9 # "event" act.target_object_id = evt.pk act.timestamp = dt act.save()
def purge(self, *app_labels, **options): print 'Purging Activities' Activity.purgeOld(14)
def read(self, request, num=20): """ returns a given user's newsfeed stories (optional param specifying how many """ return Activity.getActivitiesForUser(request.user)[:int(num)]