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 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 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 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 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 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 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 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 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 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 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 bulk_upload_activities(request): path = 'bulk_upload/activities.csv' with open(path, encoding="latin-1") as f: reader = csv.reader(f) for row in reader: activity = Activity() activity.name = row[0] activity.activity_type = row[1] activity.term = row[2] activity.location = row[3] activity.suburb = row[4] activity.postcode = row[5] activity.organiser = row[6] activity.contact_number = row[7] activity.description = row[8] activity.activity_date = row[9] activity.start_date = row[10] activity.end_date = row[11] activity.start_time = row[13] activity.end_time = row[14] activity.created_by = User.objects.get(username=row[15]) # Image Upload if row[16] != '': file_dir = 'bulk_upload/images/' + row[16] image = open(file_dir, 'rb') image_file = File(image) activity.activity_img.save(row[16], image_file) # Flyer Upload if row[17] != '': file_dir = 'bulk_upload/flyers/' + row[17] flyer = open(file_dir, 'rb') flyer_file = File(flyer) activity.flyer.save(row[17], flyer_file) activity.min_age = row[18] activity.max_age = row[19] activity.background = row[20] activity.living_duration = row[21] activity.gender = row[22] if row[23] != '': activity.cost = row[23] if row[24] != '': activity.space = row[24] activity.cost_choice = row[25] activity.space_choice = row[26] activity.save() f.close() return HttpResponse("Success uploading activities.")
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 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 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 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 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 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 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 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 create(self, validated_data): print('Create activity') age = validated_data.pop('age') level = validated_data.pop('level') time = validated_data.pop('time') group = validated_data.pop('group') supervised = validated_data.pop('supervised') cost = validated_data.pop('cost') location = validated_data.pop('location') skills = validated_data.pop('skills') learning = validated_data.pop('learning') translations = validated_data.pop('translations') authors = validated_data.pop('authors') activity = Activity(**validated_data) if time: activity.time = MetadataOption.objects.get_or_create(**time)[0] if group: activity.group = MetadataOption.objects.get_or_create(**group)[0] if supervised: activity.supervised = MetadataOption.objects.get_or_create( **supervised)[0] if cost: activity.cost = MetadataOption.objects.get_or_create(**cost)[0] if location: activity.location = MetadataOption.objects.get_or_create( **location)[0] if learning: activity.learning = MetadataOption.objects.get_or_create( **learning)[0] activity.save() for age_item in age: activity.age.add( MetadataOption.objects.get_or_create(**age_item)[0]) for level_item in level: activity.level.add( MetadataOption.objects.get_or_create(**level_item)[0]) for skills_item in skills: activity.skills.add( MetadataOption.objects.get_or_create(**skills_item)[0]) for author in authors: author.update(activity=activity) activity.authors.add( AuthorInstitution.objects.get_or_create(**author)[0]) activity.save() for translation in translations: translation.update(master=activity) t = ActivityTranslation(**translation) t.save() return activity
def signup_products(request): print('inside signup_products, authentication.view') recent_challenge_feeds = Feed.get_feeds().filter( is_challenge=1).order_by('-date') if recent_challenge_feeds: users_challenges = recent_challenge_feeds else: users_challenges = [] if request.method == 'POST': form = SignUpForm(request.POST) flag = 'products' print('flag', 'products') if not form.is_valid(): return render( request, 'authentication/signup.html', { 'form_products': form, 'flag': flag, 'users_challenges': users_challenges, }) else: is_product = request.POST.get('is_product') username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') User.objects.create_user(username=username, password=password, email=email) user = authenticate(username=username, password=password) profile_pk = user.profile.pk print(profile_pk, user.username) if is_product: print('user is a product') user.profile.is_product = 1 user.save() login(request, user) profile_pk = user.profile.pk # profile_pk of newley registered user profile = user.profile # profile object of newly registered user print(profile_pk, user.username) hohos = get_object_or_404(User, username='******') hohoshelp = get_object_or_404(User, username='******') like_by_hohos = Activity(activity_type=Activity.LIKE_PROFILE, profile=profile_pk, user=hohos) like_by_hohoshelp = Activity(activity_type=Activity.LIKE_PROFILE, profile=profile_pk, user=hohoshelp) like_by_hohos.save() like_by_hohoshelp.save() hohos.profile.notify_liked_profile( profile) # hohos to=> user(newly registered) hohoshelp.profile.notify_liked_profile( profile) # hohoshelp to user(newly registered) like = Activity(activity_type=Activity.LIKE_PROFILE, profile=profile_pk, user=user) like.save() to_user = user from_user = get_object_or_404(User, username='******') if from_user: welcome_post = 'Hey ' + to_user.username + ' Get ready to solve your customers issues.' feed = Feed() feed.user = from_user feed.to_user = to_user to_user_profile_pk = profile_pk # newley registered users profile pk feed.profile_pk = to_user_profile_pk feed.post = welcome_post feed.save() wrote_on_profile = Activity( activity_type=Activity.WROTE_ON_PROFILE, profile=to_user_profile_pk, user=from_user) wrote_on_profile.save() hohos.profile.notify_wrote_on_profile(profile, feed) messages.add_message( request, messages.SUCCESS, 'Hey ,' + user.username + '\n Its what people and products are talking about, \ See what people are talking with your friend products\ You are live now you can talk to the people who use you\ and people can talk you on your live profile!' ) from_email = django_settings.EMAIL_HOST_USER to = [email] subject = 'Welcome at hohos ' + user.username message = 'Dear '+user.username+'!\n'\ + 'We are happy to see you on hohos.\n' \ + 'You will have lots of amazing experience along the time. It will get better if '\ + 'people using you start sharing their feedback\n'\ + 'This will help you become better and more efficient'\ + 'This way both you and customers may get the best of available\n'\ + 'Moreover you can become the part of OpenChat community at - hohos.tech/feeds/openchat/h_h/ '\ + ' here You can talk to your daily use products too. Which makes things a lot easier.\n\n'\ + 'Build you profile for better interaction.'\ + 'First hohos.tech/login and then move to hohos.tech/settings/human/\n\n'\ + 'Best wishes!\n'\ + '-Team iA at hohos.tech' if to: try: send_mail(subject, message, from_email, to, fail_silently=False) except: pass print('inside signup, authentication.views') print('user\'s pk %d' % (user.pk)) return redirect('/feeds/openchat/h_p/') else: return render(request, 'authentication/signup.html', { 'form_products': SignUpForm(), 'users_challenges': users_challenges, })
def signup_human(request): print('inside signup_human, authentication.view') recent_challenge_feeds = Feed.get_feeds().filter( is_challenge=1).order_by('-date')[:20] if recent_challenge_feeds: users_challenges = recent_challenge_feeds else: users_challenges = [] if request.method == 'POST': form = SignUpForm(request.POST) flag = 'human' print('flag', flag) if not form.is_valid(): return render( request, 'authentication/signup.html', { 'form_human': form, 'flag': flag, 'users_challenges': users_challenges, }) else: username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') gender = form.cleaned_data.get('gender') User.objects.create_user( username=username, password=password, email=email) # removed email at signup to make signup fast user = authenticate(username=username, password=password) user.profile.gender = gender user.save() login(request, user) profile_pk = user.profile.pk # profile_pk of newley registered user profile = user.profile # profile object of newly registered user print(profile_pk, user.username) hohos = get_object_or_404(User, username='******') hohoshelp = get_object_or_404(User, username='******') like_by_hohos = Activity(activity_type=Activity.LIKE_PROFILE, profile=profile_pk, user=hohos) like_by_hohoshelp = Activity(activity_type=Activity.LIKE_PROFILE, profile=profile_pk, user=hohoshelp) like_by_hohos.save() like_by_hohoshelp.save() hohos.profile.notify_liked_profile( profile) # hohos to=> user(newly registered) hohoshelp.profile.notify_liked_profile( profile) # hohoshelp to user(newly registered) like = Activity(activity_type=Activity.LIKE_PROFILE, profile=profile_pk, user=user) like.save() to_user = user from_user = hohos # get_object_or_404(User, username='******') wel_post = '' welcome1= ' You seem to love facial expressions?? You can Make it awesome!\n'\ +'Challenge your friends and imitate them. Sounds cool??\n'\ +'Welcome!\nhttp://www.hohos.tech/feeds/challenge/' welcome2= ' Get ready to speak through your awesome facial expressions...\n'\ +'http://www.hohos.tech/feeds/' welcome3= ' You are awesome! \n'\ +'Imitate your friends expressions and challenge them yours.'\ +'You should try it once!\n'\ +'Its amazing!\nhttp://www.hohos.tech/feeds/' post_no = random.randint(1, 3) if post_no == 1: wel_post = welcome1 elif post_no == 2: wel_post = welcome2 else: wel_post = welcome3 if from_user: welcome_post = 'Hey ' + to_user.username + wel_post feed = Feed() feed.user = from_user feed.to_user = to_user to_user_profile_pk = profile_pk # newley registered users profile pk feed.profile_pk = to_user_profile_pk feed.post = welcome_post feed.save() wrote_on_profile = Activity( activity_type=Activity.WROTE_ON_PROFILE, profile=to_user_profile_pk, user=from_user) wrote_on_profile.save() hohos.profile.notify_wrote_on_profile(profile, feed) messages.add_message( request, messages.SUCCESS, 'Get ready to show your own flavours!!' + user.username + '\n If you want to make people make a special pose for you, \ just share that and see if your friends could make that better?\ you Can visit your friends profile and say something\ about him/her!') from_email = django_settings.EMAIL_HOST_USER to = [email] subject = 'Welcome at hohos ' + user.username message = 'Dear '+user.username+'!\n'\ + 'We are happy to see you on hohos.tech\n' \ + 'You will have lots of amazing experience along the time. It will get better if '\ + 'you participate in share and imitate culture at hohos.tech/feeds/\n'\ + 'Challenge your facial expressions, let your likers and other people imitate them.'\ + 'Because its awesome to see the different versions of same thing.\n'\ + 'This becomes rejoicing when your own friends imitate you.\n\n'\ + 'Moreover you can become the part of OpenChat community at - hohos.tech/feeds/openchat/h_h/ '\ + ' here You can talk to your daily use products too. Which makes things a lot easier.\n\n'\ + 'Build you profile for better interaction.'\ + 'First hohos.tech/login and then move to hohos.tech/settings/human/\n\n'\ + 'Best wishes!\n'\ + '-Team iA at hohos.tech' if to: try: send_mail(subject, message, from_email, to, fail_silently=False) except: pass # print('inside signup, authentication.views') # print('user\'s pk %d'%(user.pk)) return redirect('feeds') else: return render(request, 'authentication/signup.html', { 'form_human': SignUpForm(), 'users_challenges': users_challenges, })
def createActivity(self): activity = Activity() activity.name = 'test from function' activity.user = User.objects.get_by_natural_key('testingUser') activity.save() return activity
with open('activities_fulldata.json', encoding="utf8") as f: activity_json = json.load(f) for activity in activity_json: try: activity = Activity( person=Person.objects.get(pk=int(activity['person'])), job=Job.objects.get(pk=int(activity['job'])), start_date=activity['start_date'], end_date=activity['end_date'], activity_group=activity['activity_group'], activity_type=activity['activity_type'], start_depth=activity['start_depth'], end_depth=activity['end_depth']) activity.save() except: print("No Activity") # with open('shipments.json', encoding="utf8") as f:a # shipment_json = json.load(f) # for shipment in shipment_json: # try: # shipment = Shipment( # create_by_person=Person.objects.get( # pk=int(shipment['create_by_person'])), # received_by_person=Person.objects.get( # pk=int(shipment['received_by_person'])), # destination=shipment['destination'], # dest_type=shipment['dest_type'],
def add_test_examples(user_id): """ Creates test activities, measurements and metric examples in default project for user. If the user already has such activities then does nothing. :param user_id: user id """ example_activity = "Test Activity Example" test_examples = Activity.objects.filter(entity__name=example_activity, participation__user=user_id) if test_examples.count() == 0: with transaction.atomic(): part = UserParticipation.objects.get(user=user_id, project=None) e, created = Entity.objects.get_or_create(name=example_activity) # activities for 10 days for i in range(10): cur_day_timestamp = int(time.time() / DAY_SEC - i) * DAY_SEC # ten activities per day for j in range(10): a = Activity(participation=part, entity=e) a.save() start_time = cur_day_timestamp + rnd.randint( 9 * 60 * 60, 18 * 60 * 60) end_time = start_time + rnd.randint(60 * 60, 2 * 60 * 60) Measurement(type='int', name='int property 1', value=str(rnd.randint(0, 100)), activity=a).save() Measurement(type='int', name='int property 2', value=str(rnd.randint(0, 100)), activity=a).save() Measurement(type='long', name='start time', value=str(start_time * 1000), activity=a).save() Measurement(type='long', name='end time', value=str(end_time * 1000), activity=a).save() p1 = Metric(name='Tst activity prop 1', type=Metric.RAW, participation=part, info={ "field": "int property 1", "filters": {}, "activity": example_activity }) p2 = Metric(name='Tst activity prop 2', type=Metric.RAW, participation=part, info={ "field": "int property 2", "filters": {}, "activity": example_activity }) p1.save() p2.save() c1 = Metric(name='Tst props diff', type=Metric.COMPOSITE, participation=part, info={ "bounds": {}, "groupby": {}, "aggregate": "minus", "components": [p1.id, p2.id], "gqm": { "gqm_goal": "Show activity difference", "gqm_question": "What is difference per activity?" } }) c2 = Metric(name='Tst diff by day', type=Metric.COMPOSITE, participation=part, info={ "bounds": { "lower": 20, "upper": 80 }, "gqm": { "gqm_goal": "Show activity difference", "gqm_question": "How much per day?" }, "groupby": { "group_func": "sum", "group_type": "day", "group_timefield": "start time" }, "aggregate": "minus", "components": [p1.id, p2.id] }) c3 = Metric(name='Tst diff by 3 days', type=Metric.COMPOSITE, participation=part, info={ "bounds": {}, "groupby": { "group_func": "sum", "group_type": "3_days", "group_timefield": "start time" }, "aggregate": "minus", "components": [p1.id, p2.id] }) c1.save() c2.save() c3.save() c4 = Metric(name='Tst diff mult', type=Metric.COMPOSITE, participation=part, info={ "bounds": { "lower": 0, "upper": 1000000 }, "groupby": {}, "aggregate": "mult", "components": [c2.id, c2.id], "gqm": { "gqm_goal": "Show activity difference", "gqm_question": "What is difference per activity?" } }) c5 = Metric(name='Tst one', type=Metric.COMPOSITE, participation=part, info={ "bounds": { "lower": 0, "upper": 2 }, "groupby": {}, "aggregate": "div", "gqm": { "gqm_goal": "Show positive values", "gqm_question": "Is it equal to one?" }, "components": [c2.id, c2.id] }) c4.save() c5.save()