def like(request, username, slug): authenticated_user = get_authenticated_user(request) person = get_object_or_404(Person, username=username) # Get the Person post = get_object_or_404(Post, author=person, slug=slug) # Get the Post # If user has liked post before if post in authenticated_user.liked_posts.all(): post.likes.remove(authenticated_user) post.len_likes = int(post.len_likes) - 1 authenticated_user.liked_posts.remove(post) responseText = f'<button class="btn btn-light me-2" type="button" onclick="likePost(\'{post.author.username}\', \'{post.slug}\', \'{post.id}\')"><i class="far fa-heart"></i> <span class="fa-num">{post.len_likes}</span></button>' # If user has not liked post before else: post.likes.add(authenticated_user) post.len_likes = int(post.len_likes) + 1 authenticated_user.liked_posts.add(post) responseText = f'<button class="btn btn-outline-danger me-2" type="button" onclick="likePost(\'{post.author.username}\', \'{post.slug}\', \'{post.id}\')"><i class="fas fa-heart"></i> <span class="fa-num">{post.len_likes}</span></button>' notif = Notification( receiver=post.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> مطلب «<a href="/user/{username}/post/{slug}/">{post.title}</a>» شما را پسند کرد', notif_type='like') notif.save() authenticated_user.save() post.save() # Response the data return HttpResponse(responseText)
def follow_person(request, username, url): person = Person.objects.get(username = username) user = Person.objects.get(username = request.user.username) if person in user.following.all(): user.following.remove(person) user.len_following = int(user.len_following) - 1 person.followers.remove(user) person.len_followers = int(person.len_followers) - 1 else: user.following.add(person) user.len_following = int(user.len_following) + 1 person.followers.add(user) person.len_followers = int(person.len_followers) + 1 notif = Notification(givver = person, message = '<a href="/user/{0}/">{1}</a> از حالا شما را دنبال میکند'.format(user.username, user.name), notif_type = 'follow') notif.save() person.save() user.save() return HttpResponseRedirect(url.replace('%2F', '/'))
def follow_person(request, username, url): authenticated_user = get_authenticated_user(request) person = Person.objects.get(username=username) if person in authenticated_user.following.all(): authenticated_user.following.remove(person) authenticated_user.len_following = int( authenticated_user.len_following) - 1 person.followers.remove(authenticated_user) person.len_followers = int(person.len_followers) - 1 else: authenticated_user.following.add(person) authenticated_user.len_following = int( authenticated_user.len_following) + 1 person.followers.add(authenticated_user) person.len_followers = int(person.len_followers) + 1 notif = Notification( givver=person, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> از حالا شما را دنبال میکند', notif_type='follow') notif.save() person.save() authenticated_user.save() return HttpResponseRedirect(url.replace('%2F', '/'))
def ds_noti_toprovider_lostbuyer(sku): """给sku的教师发消息,减少了某学生""" notification = Notification(user=sku.provider.user, sku=sku, noti=9, open_time=timezone.now(), close_time=sku.end_time) notification.save() return True
def achievement_add(request): if request.method == 'POST': uid=request.user.id dname = Employee.objects.get(UserId=uid).DepartmentName_id sdname = Employee.objects.get(UserId=uid).SubDepartmentName_id name = request.POST['txtachievementname'] achievement = Achievement ( AchievementName = name, DepartmentName_id = dname, SubDepartmentName_id = sdname, AchievementDescription = request.POST['txtdescription'] ) achievement.save() notification = Notification( NotificationTitle = "New Achievement", NotificationDescription = name + " Added by Akshit Mithaiwala" ) notification.save() return redirect('/admin/achievement/add/') else: department_data = Department.objects.all() subdepartment_data = SubDepartment.objects.all() return render(request, 'admin/achievement-add.html', {'department_data': department_data, 'subdepartment_data': subdepartment_data})
def post_like(request, username, post_id): authenticated_user = get_authenticated_user(request) post = Post.objects.get(id=post_id) response_data = {} if request.POST.get('action') == 'post': if post in authenticated_user.liked_posts.all(): post.likes = int(post.likes) - 1 authenticated_user.liked_posts.remove(post) response_data[ 'like_btn'] = f'<button type="submit" class="btn btn-light border-gray"><i class="far fa-heart"></i> {post.likes}</button>' else: post.likes = int(post.likes) + 1 authenticated_user.liked_posts.add(post) response_data[ 'like_btn'] = f'<button type="submit" class="btn btn-light text-danger border-gray"><i class="fas fa-heart"></i> {post.likes}</button>' notif = Notification( givver=post.author, message= '<a href="/user/{0}/">{1}</a> مطلب «<a href="/user/{2}/post/{3}/">{4}</a>» شما را لایک کرد' .format(authenticated_user.username, authenticated_user.name, post.author.username, post.id, post.title), notif_type='like') notif.save() authenticated_user.save() post.save() return JsonResponse(response_data) return HttpResponseRedirect('/user/' + username + '/post/' + str(post.id))
def post_like(request, username, post_id): user = request.user person = Person.objects.get(username=user.username) person_likes = person.likes.all() post = Post.objects.get(id=post_id) if post in person_likes: post.likes = int(post.likes) - 1 person.likes.remove(post) else: post.likes = int(post.likes) + 1 person.likes.add(post) notif = Notification( givver=post.author, message= '<a href="/user/{0}/">{1}</a> مطلب «<a href="/user/{2}/post/{3}/">{4}</a>» شما را لایک کرد' .format(person.username, person.name, post.author.username, post.id, post.title), notif_type='like') notif.save() person.save() post.save() return HttpResponseRedirect('/user/' + username + '/post/' + str(post.id))
def reply_comment(request, username, slug, comment_id): authenticated_user = get_authenticated_user(request) comment = get_object_or_404(Comment, id=comment_id) # Get the Comment if request.method == 'POST': form = CommentForm(request.POST) # Get form if form.is_valid(): text = form.cleaned_data['textInput'] # Read body # Create a Comment model with form data new_comment = Comment( author=authenticated_user, text=text, ) new_comment.save() # Save it # Add new comment to comment replys comment.replys.add(new_comment) notif = Notification( receiver=comment.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> پاسخی روی <a href="/user/{username}/post/{slug}/#comment_{comment.id}">نظر</a> شما ارسال کرد', notif_type='reply') notif.save() # Redirect user to 'person:post:detail' url return HttpResponseRedirect('/user/' + username + '/post/' + slug)
def add_comment(request, username, slug): authenticated_user = get_authenticated_user(request) person = get_object_or_404(Person, username=username) # Get the Person post = get_object_or_404(Post, author=person, slug=slug) # Get the Post if request.method == 'POST': form = CommentForm(request.POST) # Get form if form.is_valid(): text = form.cleaned_data['textInput'] # Read body # Create a Comment model with form data comment = Comment( author=authenticated_user, text=text, ) comment.save() # Save it post.comments.add(comment) post.len_comments = int(post.len_comments) + 1 post.save() notif = Notification( receiver=post.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> نظری روی مطلب «<a href="/user/{username}/post/{slug}/">{post.title}</a>» شما ارسال کرد', notif_type='comment') notif.save() # Redirect user to 'person:post:detail' url return HttpResponseRedirect('/user/' + username + '/post/' + slug)
def club_add(request): if request.method == 'POST': ClubImage = request.FILES['txtimageurl'] filesystem = FileSystemStorage() filename = filesystem.save(ClubImage.name, ClubImage) url = filesystem.url(filename) # Name split and join club_username = request.POST['txtclubname'].lower().split() if len(club_username) > 1: club_username = club_username[0] + "@events.com" else: club_username = "".join(club_username) + "@events.com" alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(10)) userId = request.user.id student = Student.objects.get(UserId_id=userId) email = student.StudentEmail # User Creation user = User.objects.create_user( club_username, email, password ) club = Club( ClubName=request.POST['txtclubname'], ClubType=request.POST['txtclubtype'], ClubImageName=filename, ClubImage=url, DepartmentName_id=request.POST['dropdowndepartment'], FacebookLink=request.POST['txtfacebook'], InstagramLink=request.POST['txtinstagram'], TwitterLink=request.POST['txttwitter'], DribbbleLink=request.POST['txtdribbble'] ) clubMember = ClubMember( ClubId=club, StudentId=student, MemberRole='Club Admin' ) group = Group.objects.get(name="clubAdmin") user.groups.add(group) user.save() club.save() clubMember.save() notification = Notification( NotificationTitle="New Club", NotificationDescription=name + "Added by " + request.user.first_name ) notification.save() return redirect('/admin/club/add/') else: department_data = Department.objects.all() notification_data = Notification.objects.all().order_by( '-NotificationDateTime')[:3] return render(request, 'admin/club-add.html', {'department_data': department_data, 'notification_data': notification_data})
def ds_noti_tobuyer_noprovider(sku): """给学生发一个 noti 说完蛋了课不上了""" for buyer in sku.buyer.all(): notification = Notification(user=buyer.user, sku=sku, noti=6, open_time=timezone.now(), close_time=timezone.now() + datetime.timedelta(weeks=100)) notification.save() return True
def ds_noti_tobuyer_changeprovider(sku): """给学生发一个 noti 说课换老师了""" for buyer in sku.buyer.all(): notification = Notification(user=buyer.user, sku=sku, noti=5, open_time=timezone.now(), close_time=sku.start_time + datetime.timedelta(hours=1)) notification.save() return True
def student_add(request): if request.method == 'POST': StudentImage = request.FILES['txtimageurl'] filesystem = FileSystemStorage() filename = filesystem.save(StudentImage.name, StudentImage) url = filesystem.url(filename) users = User.objects.all() for user in users: if user.username == request.POST['txtusername']: messages.warning(request, "User already exist") return redirect('/admin/student/add/') # User Creation user = User.objects.create_user(request.POST['txtusername'], request.POST['txtemail'], request.POST['txtpassword']) group = Group.objects.get(name="Student") user.groups.add(group) # Name split and join Name = request.POST['txtfullname'].split() if len(Name) > 1: user.first_name = Name[0] user.last_name = " ".join(Name[1:]) else: user.first_name = " ".join(Name) user.save() student = Student( StudentName=request.POST['txtfullname'], UserId=user, # StudentUserName = request.POST['txtusername'], # StudentPassword = request.POST['txtpassword'], DepartmentName_id=request.POST['dropdowndepartment'], SubDepartmentName_id=request.POST['dropdownsubdepartment'], StudentImageName=filename, StudentImage=url, StudentGender=request.POST['gender'], StudentPhoneNumber=request.POST['txtphoneno'], StudentEmail=request.POST['txtemail'], StudentAddress=request.POST['txtaddress'], StudentCity=request.POST['txtcityname']) student.save() notification = Notification( NotificationTitle="New Student", NotificationDescription=request.POST['txtfullname'] + " Added by Akshit Mithaiwala") notification.save() return redirect('/admin/student/add/') else: department_data = Department.objects.all() subdepartment_data = SubDepartment.objects.all() return render( request, 'admin/student-add.html', { 'department_data': department_data, 'subdepartment_data': subdepartment_data })
def follow_user(follower_id, followed_id): """ ..warning:: The following problem should be resolved by @use_master decorator In production, since database is set up as master-slave, it's easy to create inconsistency. A typical situation is notification.incr_count_in_profile() gets called on master and the result on that profile is not propagated to slave(), and followed query Profile on slave, bringing in dirty data of notification_count. Also be wary of when follow_user is called together, invitor and invited follow each other right after registration. """ if follower_id == followed_id: return 'error' try: followed = Profile.objects.get(pk=followed_id) follower = Profile.objects.get(pk=follower_id) #if not followed.is_active or not follower.is_active: # return 'error' follow_relation = User_User() follow_relation.follower_id = follower_id follow_relation.followed_id = followed_id follow_relation.save() notification = Notification(operation='f') notification.user_id = followed_id notification.related_user_id = follower_id notification.save() #Increase the followed user's follower count followed.follower_count += 1 followed.notification_count += 1 followed.save() follower.following_count += 1 follower.save() user_recommendation_set = User_Recommendation.objects.filter(user__pk=follower_id, user_to_follow__pk=followed_id) if user_recommendation_set: user_recommendation = user_recommendation_set[0] #To prevent table growing too large, just delete the row; Mark deleted is only #used for people that user marked not interested. user_recommendation.delete() rc = redis.Redis(host=settings.REDIS_HOST, port=6379, db=0) key = 'user_following_' + str(follower_id) rc.zadd(key, followed_id, 1) rc.delete('news_feeds_' + str(follower_id)) except: #Fail silently since user may follow on different pages return 'success' return 'success'
def edit_language_set_root_action(user_id, topic_id, root_id): """Add/Modify an Enlish topic as language root;No root can be added for English topic""" topic = Topic.objects.get(pk=topic_id) root = Topic.objects.get(pk=root_id) if topic.language == 'en' or root.language != 'en': return '只能由非英语话题指向英语话题' else: previous_root = topic.language_set_root topic.language_set_root = root topic.save() reference = None #Initialize if previous_root: refs = Topic_Revision.objects.filter(topic__id=topic_id, operation='ml').order_by('-pk') if refs: reference = refs[0] if reference.user_id != user_id: notification = Notification(operation='ml') notification.user_id = reference.user_id notification.related_user_id = user_id notification.topic_id = topic_id notification.incr_count_in_profile() notification.save() update_user_topic_fame(topic_id, user_id, reference.user_id) else: reference = None update_user_topic_fame(topic_id, user_id) topic_revision = Topic_Revision(operation='ml', reference=reference) topic_revision.topic_id = topic_id if previous_root: topic_revision.previous_root = previous_root topic_revision.user_id = user_id topic_revision.save() return topic.pk
def add_topic_alias_action(user_id, topic_id, topic_name, alias): """return topic_alias.id(long) if succeed, otherwise return error message""" if topic_name == alias: return '别名不能与话题名相同' if alias and SensitiveWord.objects.filter(name=alias, disabled=False): return '根据当地法律,此别名不能被添加' old_aliases = Topic_Alias.objects.filter(topic__id=topic_id, alias=alias) if old_aliases: return '此别名已经添加到此话题' else: topic_alias = Topic_Alias(alias=alias) topic_alias.topic_id = topic_id topic_alias.save() refs = Topic_Revision.objects.filter(topic__id=topic_id, operation='da', alias=topic_alias.alias).order_by('-pk') if refs: reference = refs[0] if reference.user_id != user_id: notification = Notification(operation='aa') notification.user_id = reference.user_id notification.related_user_id = user_id notification.topic_id = topic_id notification.incr_count_in_profile() notification.save() update_user_topic_fame(topic_id, user_id, reference.user_id) else: reference = None update_user_topic_fame(topic_id, user_id) topic_revision = Topic_Revision(operation='aa', reference=reference) topic_revision.topic_id = topic_id topic_revision.alias = topic_alias.alias topic_revision.user_id = user_id topic_revision.save() return topic_alias.id
def delete_topic_alias_action(user_id, topic_id, alias): """ return topic_id(int) if succeed, otherwise return error message""" old_alias_set = Topic_Alias.objects.filter(topic__id=topic_id, alias=alias) if old_alias_set: old_alias = old_alias_set[0] refs = Topic_Revision.objects.filter(topic__id=topic_id, operation='aa', alias=old_alias.alias).order_by('-pk') if refs: reference = refs[0] if reference.user_id != user_id: notification = Notification(operation='da') notification.user_id = reference.user_id notification.related_user_id = user_id notification.topic_id = topic_id notification.incr_count_in_profile() notification.save() update_user_topic_fame(topic_id, user_id, reference.user_id) else: reference = None update_user_topic_fame(topic_id, user_id) topic_revision = Topic_Revision(operation='da', reference=reference) topic_revision.topic_id = topic_id topic_revision.alias = old_alias.alias topic_revision.user_id = user_id topic_revision.save() old_alias.delete() return topic_id else: return '此别名不存在'
def delete_topic_parent_action(user_id, topic_id, parent_id): """return 0(int) if succeeded, otherwise return error message""" topic_parent = Topic_Parent.objects.filter(topic__id=topic_id, parent__id=parent_id) topic_parent.delete() refs = Topic_Revision.objects.filter(topic__id=topic_id, parent__id=parent_id, operation='ap').order_by('-pk') if refs: reference = refs[0] if reference.user_id != user_id: notification = Notification(operation='dp') notification.user_id = reference.user_id notification.related_user_id = user_id notification.topic_id = topic_id notification.incr_count_in_profile() notification.save() update_user_topic_fame(topic_id, user_id, reference.user_id) else: reference = None update_user_topic_fame(topic_id, user_id) topic_revision = Topic_Revision(operation='dp', reference=reference) topic_revision.topic_id = topic_id topic_revision.parent_id = parent_id topic_revision.user_id = user_id topic_revision.save() return 0
def action(invite_id, action): invite = Invite.query.filter_by(id=invite_id).first_or_404() user = User.query.filter_by(id=invite.sender_id).first_or_404() if request.method == 'POST' and action == 'userResponse': response = request.form.get('userResponse') message = "{} has sent you a message regarding your invite \"{}\". Message: \"{}\" ".format( current_user.name, invite.heading, response) notification = Notification(author=current_user, receiver=user, message=message, type="userResponse") db.session.add(notification) db.session.commit() flash('Your response has been sent successfully.') if request.method == 'POST' and action == 'authorResponse': notif = Notification.query.filter_by(id=invite_id).first_or_404() usern = User.query.filter_by(id=notif.senderId).first_or_404() response = request.form.get('authorResponse') message = "{} has sent you a message regarding your response. Message: \"{}\" ".format( current_user.name, response) notification = Notification(author=current_user, receiver=usern, message=message, type="authorResponse") db.session.add(notification) db.session.commit() if action == 'accept': message = "{} has accepted your invitation\n Heading:{}. \n Details:{}".format( current_user.name, invite.heading, invite.details) invite.accepted = True notification = Notification(author=current_user, receiver=user, message=message, type="accept") db.session.add(notification) current_user.accept_invite(invite) db.session.commit() if action == 'reject': message = "{} has rejected your invitation. Heading:{} Details:{}".format( current_user.name, invite.heading, invite.details) invite.rejected = True notification = Notification(author=current_user, receiver=user, message=message, type="reject") db.session.add(notification) current_user.reject_invite(invite) db.session.commit() return redirect(request.referrer)
def add_topic_parent_action(user_id, topic_id, parent_id=0, parent_name=''): """ Return parent_id(long) if succeed, otherwise return error message @attention: Haoliang modified the return value """ #if paernt_id is passed, we use it directly later on; Otherwise we need to add topic and get parent_id if not parent_id and not parent_name: return '上级话题不能为空' if parent_name: parent_set = Topic.objects.filter(name=parent_name) if parent_set and not parent_set[0].deleted: parent_id = parent_set[0].pk else: return_value = add_topic_action(user_id, topic_name=parent_name) if return_value['error_message']: return return_value['error_message'] else: parent_id = int(return_value['topic_id']) if topic_id == parent_id: return '不能将自身话题作为上级话题' topic_childs = Topic_Parent.objects.filter(parent__id=topic_id) for tc in topic_childs: if parent_id == tc.topic_id: return '不能将此话题下层话题作为上层话题' topic_parent = Topic_Parent.objects.filter(topic__id=topic_id, parent__id=parent_id) if topic_parent: return '请勿输入重复的父母话题' topic_parent = Topic_Parent() topic_parent.topic_id = topic_id topic_parent.parent_id = parent_id topic_parent.save() refs = Topic_Revision.objects.filter(topic__id=topic_id, parent__id=parent_id, operation='dp').order_by('-pk') if refs: reference = refs[0] if reference.user_id != user_id: notification = Notification(operation='ap') notification.user_id = reference.user_id notification.related_user_id = user_id notification.topic_id = topic_id notification.incr_count_in_profile() notification.save() update_user_topic_fame(topic_id, user_id, reference.user_id) else: reference = None update_user_topic_fame(topic_id, user_id) topic_revision = Topic_Revision(operation='ap', reference=reference) topic_revision.topic_id = topic_id topic_revision.parent_id = parent_id topic_revision.user_id = user_id topic_revision.save() return parent_id
def club_member_approval(request): if request.is_ajax(): if request.method == 'POST': club_data = ClubMemberRequest.objects.get( id=request.POST['request_id'] ) student = Student.objects.get( StudentId=club_data.StudentId_id) club = Club.objects.get( ClubName=club_data.ClubId_id) if request.POST['status'] == "approve": clubMember = ClubMember( ClubId=club, StudentId=student, MemberRole='Club Member' ) clubMember.save() notification = Notification( NotificationTitle="New Club Member ", NotificationDescription=club_data.ClubId_id + " Added by " + student.StudentName ) notification.save() club_request = ClubMemberRequest.objects.get( pk=request.POST['request_id']) club_request.delete() send_mail( 'Club Member Proposal', f'We are Glad to inform you that you are member of Club "{club.ClubName}"', '*****@*****.**', [student.StudentEmail], fail_silently=False, ) return JsonResponse({}, status=200) else: club_request = ClubMemberRequest.objects.get( pk=request.POST['request_id']) club_request.delete() send_mail( 'Club Member Proposal', f'We are sorry to inform you that Club "{club.ClubName}" denied your proposal', '*****@*****.**', [student.StudentEmail], fail_silently=False, ) return JsonResponse({}, status=200) return JsonResponse({}, status=500)
def delete_topic_action(user_id, topic_id, comment=''): """" Args: topic_id: integer comment: string Return: Success: 0(int) Failed: error_message(string) TODO: limit the privilege of deleting large topics to only admin or user with good reputation. """ topic = Topic.objects.get(pk=topic_id) if topic: if topic.locked: return '此话题已被锁定,只有管理员可以更改' elif not topic.deleted: topic.deleted = True topic.save() item_topic_set = Item_Topic.objects.filter(topic__id=topic.pk) if item_topic_set: # TODO how to improve efficiency of bulk updating for item_topic in item_topic_set: item_topic.topic_deleted = True item_topic.save() topic_parent_set = Topic_Parent.objects.filter(parent__id=topic.pk) if topic_parent_set: for topic_parent in topic_parent_set: topic_parent.parent_deleted = True topic_parent.save() refs = Topic_Revision.objects.filter(topic__id=topic.pk, operation='a').order_by('-pk') if refs: reference = refs[0] if reference.user_id != user_id: notification = Notification(operation='d') notification.user_id = reference.user_id notification.related_user_id = user_id notification.topic_id = topic_id notification.incr_count_in_profile() notification.save() update_user_topic_fame(topic_id, user_id, reference.user_id) else: reference = None update_user_topic_fame(topic_id, user_id) topic_revision = Topic_Revision(operation='d', reference=reference, comment=comment) topic_revision.topic_id = topic.pk topic_revision.user_id = user_id topic_revision.save() return 0 else: return '此话题已被删除' else: return '话题不存在'
def unmerge_topic_action(user_id, topic_id, comment=''): """ return topic_id(int) if succeed, return error message if failed""" topic = Topic.objects.get(pk=topic_id) merged_to_id = topic.merged_to_id if topic: if topic.locked or topic.deleted: return '此话题已被锁定或被删除' elif topic.merged_to_id: topic.merged_to_id = None topic.save() #Note: If topic A is merged to me, me is merged to topic B, then A is merged to B #Now me unmerges from B, but let A stay merged to B item_topic_set = Item_Topic.objects.filter(topic_merged_from__id=topic_id) if item_topic_set: for item_topic in item_topic_set: item_topic.topic_id = item_topic.topic_merged_from_id item_topic.topic_merged_from_id = None item_topic.save() topic_parent_set = Topic_Parent.objects.filter(parent_merged_from__id=topic_id) if topic_parent_set: for topic_parent in topic_parent_set: topic_parent.parent_id = topic_parent.parent_merged_from_id topic_parent.parent_merged_from_id = None topic_parent.save() refs = Topic_Revision.objects.filter(topic__id=topic_id, operation='m').order_by('-pk') if refs: reference = refs[0] if reference.user_id != user_id: notification = Notification(operation='um') notification.user_id = reference.user_id notification.related_user_id = user_id notification.topic_id = topic_id notification.incr_count_in_profile() notification.save() update_user_topic_fame(topic_id, user_id, reference.user_id) else: reference = None update_user_topic_fame(topic_id, user_id) topic_revision = Topic_Revision(operation='um', reference=reference, comment=comment) topic_revision.topic_id = topic_id topic_revision.user_id = user_id topic_revision.merged_to_id = merged_to_id topic_revision.save() return topic_id else: return '此话题没被合并' else: return '话题不存在'
def event_add(request): if request.is_ajax(): if request.method == 'POST': try: EventImage = request.FILES['txtimageurl'] filesystem = FileSystemStorage() filename = filesystem.save(EventImage.name, EventImage) url = filesystem.url(filename) userId = request.user.id club = Club.objects.get(UserId_id=userId) name = request.POST['txteventname'] event = Event( title=name, ClubName_id=club.ClubName, VenueId_id=request.POST['dropdownvenue'], EventType=request.POST['eventtype'], EventImageName=filename, EventImage=url, EventEligibility=request.POST['eventeligibility'], start=request.POST['txtstartdate'], end=request.POST['txtenddate'], EventStartTime=request.POST['txtstarttime'], EventEndTime=request.POST['txtendtime'], EventDescription=request.POST['txtdescription'], EventAmount=request.POST['txtamount'] ) event.save() notification = Notification( NotificationTitle="New Event", NotificationDescription=name + " Added by " + club.ClubName ) notification.save() send_emails( 'New Event', f'New Event "{event.title}" Has Been Formed By Club "{club.ClubName}" Checkout The Webiste To Know More') except: return JsonResponse({'error': 'Something Went Wrong'}, status=500) return JsonResponse({'msg': 'New Event Has Been Created'}, status=200) club_data = Club.objects.all() venue_data = Venue.objects.all() return render(request, 'admin/event-add.html', {'club_data': club_data, 'venue_data': venue_data})
def club_add(request): if request.method == 'POST': ClubImage = request.FILES['txtimageurl'] filesystem = FileSystemStorage() filename = filesystem.save(ClubImage.name, ClubImage) url = filesystem.url(filename) userId = request.user.id student = Student.objects.get(UserId_id=userId) club = Club ( ClubName = request.POST['txtclubname'], ClubType = request.POST['txtclubtype'], ClubImageName = filename, ClubImage = url, DepartmentName_id = request.POST['dropdowndepartment'], FacebookLink = request.POST['txtfacebook'], InstagramLink = request.POST['txtinstagram'], TwitterLink = request.POST['txttwitter'], DribbbleLink = request.POST['txtdribbble'] ) clubMember = ClubMember( ClubId = club, StudentId = student, MemberRole = 'Club Admin' ) group = Group.objects.get(name="clubAdmin") request.user.groups.add(group) club.save() clubMember.save() notification = Notification( NotificationTitle = "New Club", NotificationDescription = name + "Added by " + request.user.first_name ) notification.save() return redirect('/admin/club/add/') else: department_data = Department.objects.all() notification_data = Notification.objects.all().order_by('-NotificationDateTime')[:3] return render(request, 'admin/club-add.html', {'department_data': department_data, 'notification_data': notification_data})
def clubmember_add(request): if request.method == 'POST': clubname = request.POST['dropdownclub'] student_id = request.POST['dropdownstudent'] clubmember = ClubMember( ClubId_id=clubname, StudentId_id=student_id, MemberRole=request.POST['txtrole'] ) clubmember.save() notification = Notification( NotificationTitle="New Club member", StudentId_id=student_id, NotificationDescription=clubname + " Added by Akshit Mithaiwala" ) notification.save() return redirect('/admin/clubmember/add/') else: club_data = Club.objects.all() student_data = Student.objects.all() return render(request, 'admin/clubmember-add.html', {'club_data': club_data, 'student_data': student_data})
def achiever_add(request): if request.method == 'POST': achievement_id = request.POST['dropdownachievement'] student_id = request.POST['dropdownstudent'] achiever = Achiever ( AchievementId_id = achievement_id, StudentId_id = student_id ) achiever.save() notification = Notification( NotificationTitle = "New Achiever", AchievementId_id = achievement_id, StudentId_id = student_id, NotificationDescription = " Added by Akshit Mithaiwala" ) notification.save() return redirect('/admin/achiever/add/') else: achievement_data = Achievement.objects.all() student_data = Student.objects.all() return render(request, 'admin/achiever-add.html', {'achievement_data': achievement_data, 'student_data': student_data})
def event_add(request): if request.method == 'POST': EventImage = request.FILES['txtimageurl'] filesystem = FileSystemStorage() filename = filesystem.save(EventImage.name, EventImage) url = filesystem.url(filename) name = request.POST['txteventname'] event = Event ( title = name, ClubName_id = request.POST['dropdownclub'], VenueId_id = request.POST['dropdownvenue'], EventType = request.POST['eventtype'], EventImageName = filename, EventImage = url, EventEligibility = request.POST['eventeligibility'], start = request.POST['txtstartdate'], end = request.POST['txtenddate'], EventStartTime = request.POST['txtstarttime'], EventEndTime = request.POST['txtendtime'], EventDescription = request.POST['txtdescription'], EventAmount = request.POST['txtamount'] ) event.save() notification = Notification( NotificationTitle = "New Event", NotificationDescription = name + " Added by Akshit Mithaiwala" ) notification.save() return redirect('/admin/event/add/') else: club_data = Club.objects.all() venue_data = Venue.objects.all() return render(request, 'admin/event-add.html', {'club_data': club_data, 'venue_data': venue_data})
def like_action(article_id, action): article = Article.query.filter_by(id=article_id).first_or_404() if action == 'like': if current_user.id != article.user_id: message = "{} liked your article titled \"{}\"".format( current_user.username, article.title) user = User.query.filter_by(id=article.user_id).first_or_404() notification = Notification(author=current_user, receiver=user, message=message) db.session.add(notification) current_user.like_article(article) db.session.commit() if action == 'unlike': current_user.unlike_article(article) db.session.commit() return redirect(request.referrer)
def add_user(email, password): """ Adds user to database and populates their email and pw :param email: email string :param password: plain text pw :return: person object """ # Instantiate main and populate fields person = User() person.notifications = [Notification()] person.linked_platforms = [] platform_arr = ['fb', 'yt', 'netflix', 'google'] # Create placeholder for platforms for platform in platform_arr: platform_obj = LinkedPlatform() platform_obj.platform = platform person.linked_platforms.append(platform_obj) for lp in person.linked_platforms: data_obj = Data() lp.data = [data_obj] # Create placeholder for summary stats person.summary_stats = [SummaryStats()] for sp in person.summary_stats: sp.timestamp = timezone.now() sp.fb = FacebookEntry() sp.yt = YTEntry() sp.netflix = NetflixEntry() sp.google = GoogleEntry() person.username = email person.password = password person.save() return person
def club_approval(request): if request.is_ajax(): if request.method == 'POST': club_data = ClubRequest.objects.get( id=request.POST['request_id'] ) student = Student.objects.get( StudentId=club_data.StudentId_id) if request.POST['status'] == "approve": user = User.objects.create_user( club_data.ClubUserName, club_data.ClubEmail, club_data.ClubPassword) group = Group.objects.get(name="clubAdmin") user.groups.add(group) club = Club( ClubName=club_data.ClubName, UserId=user, ClubType=club_data.ClubType, ClubImageName=club_data.ClubImageName, ClubImage=club_data.ClubImage, DepartmentName_id=club_data.DepartmentName_id ) clubMember = ClubMember( ClubId=club, StudentId=student, MemberRole='Club Admin' ) user.save() club.save() clubMember.save() notification = Notification( NotificationTitle="New Club ", NotificationDescription=f'{club_data.ClubName} Approved by {request.user.first_name} {request.user.last_name}!' ) notification.save() club_request = ClubRequest.objects.get( pk=request.POST['request_id']) club_request.delete() send_mail( 'Club Proposal', f'We are Glad to inform you that your proposal has been accepted for Club "{club.ClubName}"!', '*****@*****.**', [student.StudentEmail], fail_silently=False, ) send_emails( 'New Club', f'New Club "{club.ClubName}" Has Been Formed Checkout The Webiste To Know More') return JsonResponse({}, status=200) else: club_request = ClubRequest.objects.get( pk=request.POST['request_id']) filesystem = FileSystemStorage() club_request.delete() filesystem.delete(club_request.ClubImageName) send_mail( 'Club Proposal', f'We are sorry to inform you that your proposal has been denied for Club "{club.ClubName}"', '*****@*****.**', [student.StudentEmail], fail_silently=False, ) return JsonResponse({}, status=200) return JsonResponse({}, status=500)
def post_detail(request, username, post_id): person = Person.objects.get(username=username) # Get the Person post = get_object_or_404(Post, author=person, id=post_id) # Get the Post comments = PostComment.objects.filter(place=post).order_by( 'id') # Get the Comments len_comments = len(comments) # Get length of comments try: user = Person.objects.get(username=request.user.username) except: user = None post.views = int(post.views) + 1 post.save() authenticated_user = None if request.user.is_authenticated: authenticated_user = Person.objects.get(username=request.user.username) authenticated_user.viewed_posts.add(post) authenticated_user.save() # For comment # If form method == POST if request.method == 'POST': print('post') form = CommentForm(request.POST) # Get form if form.is_valid(): print('valid') mode = form.cleaned_data['mode'] # Read mode text = form.cleaned_data['text'] # Read body text = text.replace('<', '<').replace('>', '>').replace( '\n', '<br/>') # Clean the body and recognize line breaks # If mode == comment if mode == 'comment': # Create a Comment model with form data comment = PostComment(place=post, author=user, text=text, replay=None) comment.save() # Save it post.comments = int(post.comments) + 1 post.save() notif = Notification( givver=post.author, message= '<a href="/user/{0}/">{1}</a> نظری روی مطلب «<a href="/user/{2}/post/{3}/">{4}</a>» شما ارسال کرد' .format(user.username, user.name, post.author.username, post.id, post.title, comment.id), notif_type='comment') notif.save() elif mode == 'hello': return HttpResponse(json.dumps({'message': 'hello'})) else: comment = PostComment.objects.get(id=mode) comment.replay = text comment.save() notif = Notification( givver=comment.author, message= '<a href="/user/{0}/">{1}</a> پاسخی به <a href="/user/{2}/post/{3}/#comments">نظر</a> شما داد' .format(person.username, person.name, post.author.username, post.id), notif_type='replay') notif.save() context = { 'post': post, 'comments': comments, 'len_comments': len_comments, 'form': form, 'current_url': str(request.path).replace('/', '%2F'), } mskf.add_notification_availability_to_context(request, context) mskf.add_authenticated_user_to_context(request, context) mskf.add_3_ads_to_context(context) return HttpResponseRedirect('/user/' + post.author.username + '/post/' + str(post.id)) else: print(form.cleaned_data['text']) # If form method == GET else: form = CommentForm() # Give form to user post_body = mskf.get_repo_data(post.body) context = { 'post': post, 'post_body': post_body, 'comments': comments, 'len_comments': len_comments, 'form': form, 'person': user, 'current_url': str(request.path).replace('/', '%2F'), } mskf.add_notification_availability_to_context(request, context) mskf.add_authenticated_user_to_context(request, context) mskf.add_3_ads_to_context(context) return render(request, 'post_detail.html', context)
def post_detail(request, username, post_id): authenticated_user = get_authenticated_user(request) person = Person.objects.get(username=username) # Get the Person post = get_object_or_404(Post, author=person, id=post_id) # Get the Post comments = Comment.objects.filter(place=post).order_by( 'id') # Get the Comments len_comments = len(comments) # Get length of comments post.views = int(post.views) + 1 post.save() if authenticated_user is not None: authenticated_user.viewed_posts.add(post) authenticated_user.save() # For comment # If form method == POST if request.method == 'POST': form = CommentForm(request.POST) # Get form if form.is_valid(): mode = form.cleaned_data['mode'] # Read mode text = form.cleaned_data['text'] # Read body text = text.replace('<', '<').replace('>', '>').replace( '\n', '<br/>') # Clean the body and recognize line breaks # If mode == comment if mode == 'comment': # Create a Comment model with form data comment = Comment(place=post, author=authenticated_user, text=text) comment.save() # Save it post.comments = int(post.comments) + 1 post.save() notif = Notification( givver=post.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> نظری روی مطلب «<a href="/user/{post.author.username}/post/{post.id}/">{post.title}</a>» شما ارسال کرد', notif_type='comment') notif.save() else: replay = Comment(author=authenticated_user, text=text) replay.save() comment = Comment.objects.get(id=mode) comment.replays.add(replay) comment.save() post.comments = int(post.comments) + 1 post.save() notif = Notification( givver=comment.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> پاسخی به <a href="/user/{post.author.username}/post/{post.id}/#comments">نظر</a> شما داد', notif_type='replay') notif.save() notif2 = Notification( givver=post.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> نظری روی مطلب «<a href="/user/{post.author.username}/post/{post.id}/">{post.title}</a>» شما ارسال کرد', notif_type='comment') notif2.save() return HttpResponseRedirect('/user/' + post.author.username + '/post/' + str(post.id)) # If form method == GET else: form = CommentForm() # Give form to user context = { 'authenticated_user': authenticated_user, 'new_notifications': get_new_notifications(authenticated_user), 'post': post, 'post_body': translate_to_html(post.body), 'comments': comments, 'len_comments': len_comments, 'form': form, 'ads_list': ads_list(), 'current_url': str(request.path).replace('/', '%2F'), } return render(request, 'post/detail.html', context)
def merge_topic_action(user_id, topic_id, merged_to_id, comment=''): """All args are integer; return topic_id(int) if succeded, otherwise return error message""" if topic_id == merged_to_id: return '不能合并到自身话题' topic = Topic.objects.get(pk=topic_id) if topic: if topic.locked or topic.deleted: return '此话题已被锁定或被删除' elif not topic.merged_to_id: merge_to_topic = Topic.objects.get(pk=merged_to_id) if not merge_to_topic or merge_to_topic.deleted: return '要合并到的话题不存在或已被删除' #Find the topic that should really be merged to; #Should not be normal flow since merged topic won't show up in query suggestion, just in case if merge_to_topic.merged_to_id: merged_to_id = merge_to_topic.merged_to_id topic.merged_to_id = merged_to_id topic.save() #Modify the topics that are merged to me merge_to_me_topics = Topic.objects.filter(merged_to__id=topic_id) if merge_to_me_topics: for mt in merge_to_me_topics: mt.merged_to_id = merged_to_id mt.save() item_topic_set = Item_Topic.objects.filter(topic__id=topic_id) if item_topic_set: for item_topic in item_topic_set: existing_item_topic = Item_Topic.objects.filter(item__id=item_topic.item_id, topic__id=merged_to_id) if not existing_item_topic: item_topic.topic_merged_from_id = item_topic.topic_id item_topic.topic_id = merged_to_id item_topic.save() topic_parent_set = Topic_Parent.objects.filter(parent__id=topic_id) if topic_parent_set: for topic_parent in topic_parent_set: topic_parent.parent_merged_from_id = topic_parent.parent_id topic_parent.parent_id = merged_to_id topic_parent.save() refs = Topic_Revision.objects.filter(topic__id=topic_id, operation='um').order_by('-pk') if refs: reference = refs[0] if reference.user_id != user_id: notification = Notification(operation='m') notification.user_id = reference.user_id notification.related_user_id = user_id notification.topic_id = topic_id notification.incr_count_in_profile() notification.save() update_user_topic_fame(topic_id, user_id, reference.user_id) else: reference = None update_user_topic_fame(topic_id, user_id) topic_revision = Topic_Revision(operation='m', reference=reference, comment=comment) topic_revision.topic_id = topic_id topic_revision.user_id = user_id topic_revision.merged_to_id = merged_to_id topic_revision.save() return topic_id else: return '此话题已被合并,不能重复操作' else: return '话题不存在'
def ds_noti_newreply(reply, user, type): noti = 0 if type == 1 else 10 notification = Notification(user=user, reply=reply, sku=reply.sku, open_time = timezone.now(), close_time = timezone.now() + datetime.timedelta(weeks=100), noti=noti) notification.save() return True
def ds_noti_toprovider_skubooked(sku): """跟教师发通知说sku已被预订""" notification = Notification(user=sku.provider.user, sku=sku, noti=8, open_time=timezone.now(), close_time=sku.end_time) notification.save() return True
def add_topic_action(user_id, topic_id=0, topic_name='', comment=''): """ Used by add_topic(indirecly used by add_item_topic) and add_topic_parent; either topic_id or topic_name is passed. if topic_id is passed, revert deleting this topic; \ if topic_name is passed, add this topic. Return: #. Success: return_value['topic_id'] (long type) #. Failed: return_value['error_message'] (string) """ return_value = {} return_value['error_message'] = '' if not topic_id and not topic_name.strip(): return '话题名不能为空' if topic_name: #Get the topic by name since 1,the topic is deleted and not shown in query suggestion; #2,Ajax is too slow to show it topic_set = Topic.objects.filter(name=topic_name) if topic_set: topic = topic_set[0] else: topic = None else: topic = Topic.objects.get(pk=topic_id) if topic: if topic.locked: return_value['error_message'] = '此话题已被锁定,只有管理员可以更改' return return_value elif topic.deleted: #undelete the topic topic.deleted = False topic.save() item_topic_set = Item_Topic.objects.filter(topic__id=topic.pk) if item_topic_set: for item_topic in item_topic_set: item_topic.topic_deleted = False item_topic.save() topic_parent_set = Topic_Parent.objects.filter(parent__id=topic.pk) if topic_parent_set: for topic_parent in topic_parent_set: topic_parent.parent_deleted = False topic_parent.save() refs = Topic_Revision.objects.filter(topic__id=topic.pk, operation='d').order_by('-pk') if refs: reference = refs[0] if reference.user_id != user_id: notification = Notification(operation='a') notification.user_id = reference.user_id notification.related_user_id = user_id notification.topic_id = topic.pk notification.incr_count_in_profile() notification.save() update_user_topic_fame(topic_id, user_id, reference.user_id) else: reference = None update_user_topic_fame(topic_id, user_id) topic_revision = Topic_Revision(operation='a', reference=reference, comment=comment) topic_revision.topic_id = topic.pk topic_revision.user_id = user_id topic_revision.save() return_value['topic_id'] = topic.pk return return_value else: return_value['error_message'] = '此话题已存在' return return_value elif topic_name: #The topic name does not exist, add brand new topic if len(topic_name) > 25: #Each Chinese character only counts 1 here return_value['error_message'] = '话题名字过长' return return_value topic_with_alias_set = Topic_Alias.objects.filter(alias=topic_name) if topic_with_alias_set: topic_with_alias = topic_with_alias_set[0] return_value['error_message'] = '此话题已作为话题' + topic_with_alias.topic.name.encode('utf-8') + '的别名存在' return return_value if SensitiveWord.objects.filter(name=topic_name, disabled=False): return_value['error_message'] = '根据当地法律,此话题不能被添加' return return_value topic = Topic(name=topic_name) #Automatically detects whether the language is in ASCII, if not, set to be Chinese #TODO:Need to add ability of detecting more languages is_English = True for char in topic_name: if ord(char) >= 128: is_English = False break if is_English: topic.language = 'en' else: topic.language = 'zh' topic.creator_id = user_id topic.follower_count = 1 #creator automatically follows this topic topic.save() user_topic = User_Topic() user_topic.user_id = user_id user_topic.topic_id = topic.pk user_topic.save() update_user_topic_fame(topic.pk, user_id) topic_revision = Topic_Revision(operation='a') topic_revision.topic_id = topic.pk topic_revision.user_id = user_id topic_revision.save() return_value['topic_id'] = topic.pk return return_value else: #The passed in value is topic_id but it does not exist return_value['error_message'] = '此话题不存在,不能重新添加' return return_value