예제 #1
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)
예제 #2
0
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', '/'))
예제 #3
0
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)
예제 #4
0
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)
예제 #5
0
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)
예제 #6
0
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', '/'))
예제 #7
0
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))
예제 #8
0
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))
예제 #9
0
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})
예제 #10
0
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})
예제 #11
0
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
            })
예제 #12
0
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)
예제 #13
0
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)
예제 #14
0
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})
예제 #15
0
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
예제 #16
0
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})
예제 #17
0
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})
예제 #18
0
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})
예제 #19
0
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})
예제 #20
0
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('<', '&lt;').replace('>', '&gt;').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)
예제 #21
0
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('<', '&lt;').replace('>', '&gt;').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)
예제 #22
0
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)