def save(self): if self.id is None: thread = Thread(type='comment') thread.save() self.comments = thread self.check() super(Problem, self).save()
def save(self): self.check() if self.id is None: thread = Thread(type='forum') thread.save() self.thread = thread super(ForumThread, self).save()
def create(self, validated_data): name = validated_data['name'] forum_slug = validated_data['forum'] content = validated_data['content'] # Get forum object try: forum = Forum.objects.get(slug=forum_slug) except Forum.DoesNotExist: raise serializers.ValidationError( 'Forum does not exist, please enter correct forum slug') # Get the requesting user user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user else: raise serializers.ValidationError( 'Must be authenticated to create thread') # Create the thread thread = Thread(name=name, forum=forum, content=content, creator=user) thread.save() return thread
def start_new_thread(request, pk): thread_category = ThreadCategory.objects.get(pk=pk) if request.method == 'POST': form = forms.AddThread(request.POST) if form.is_valid(): new_thread = Thread(name=form.cleaned_data['name'], creator=request.user, thread_category=thread_category) new_thread.save() first_comment = ThreadComment( thread=new_thread, poster=request.user, text_content=form.cleaned_data['first_comment']) first_comment.save() return redirect('threads:thread', pk=new_thread.pk) else: # TODO add error page print('error creating thread - need to have page here') elif request.method == 'GET': form = forms.AddThread() return render(request, 'threads/start_new_thread.html', context={ 'thread_category': thread_category, 'form': form })
def save(self): thread = Thread( owner=self.profile, subject=self.cleaned_data['subject'], number_of_messages=1, active=True, ) thread.save() message = Message( body=self.cleaned_data['body'], owner=self.profile, thread=thread, ) message.save()
def post_thread(request): title = request.POST.get('title', '') topic = request.POST.get('topic', 'Current') sessionId = request.session['anon_id'] course = request.session['course_id'] is_instructor = request.session['is_instructor'] if title != '': # save the above as a thread thread = Thread.create_new_thread_with_topic(title, sessionId, course, topic, is_instructor) data = { 'message': thread.title, 'updated': naturaltime(thread.latest_reply), 'thread_id': thread.pk, 'admin_panel': '', 'replyNum': thread.getNumberOfReplies() } if request.session['is_instructor']: admin_panel = "<div class='admin-panel'><div class='delete' data-id='" + str( thread.pk ) + "' data-href='" + reverse( 'threads:delete_thread', kwargs={ 'thread_id': thread.pk, 'undo': 0 } ) + "' title='Mark thread as deleted'><i class='fa fa-remove'></i></div>" admin_panel = admin_panel + "<div class='hide' data-id='" + str( thread.pk ) + "' data-href='" + reverse( 'threads:hide_thread', kwargs={ 'thread_id': thread.pk, 'undo': 0 } ) + "' title='Hide entire thread'><i class='fa fa-eye'></i></div>" admin_panel = admin_panel + "<div class='move' data-id='" + str( thread.pk ) + "' onclick='jQuery(\".popup-background\").show(); jQuery(\".addthreadtotopic\").attr(\"action\", \"" + reverse( 'threads:new_topic', kwargs={'thread_id': thread.pk} ) + "\");return false;' title='Change thread's topic'><i class='fa fa-tag'></i></div></div>" data.update({ 'admin_panel': admin_panel, 'replies_url': reverse('threads:get_replies', kwargs={'thread_id': thread.pk}), 'post_reply_url': reverse('threads:post_reply', kwargs={'thread_id': thread.pk}) }) return HttpResponse(json.dumps(data), content_type='application/json') return render_main_thread( request, {'threads': Thread.objects.filter(topic='Current', course_id=course)})
def render_main_thread(request, context): context.update({ 'topics': Thread.getTopics(request.session['course_id']), 'mentioned_id': request.session['anon_id'], 'notifications': Notification.getNotificationsFromThreads(Thread.objects.all(), request.session['anon_id']), 'unique_key': request.session['course_id'] + context['current_topic'] }) return render(request, 'lti/index.html', context)
def setUp(self): self.u = User.objects.create_user(username="******", password="******") self.profile = UserProfile.objects.get(user=self.u) self.thread = Thread(owner=self.profile, subject="Default Thread Test") self.thread.save() self.message = Message(owner=self.profile, body="Default Reply Test", thread=self.thread) self.message.save() self.client.login(username="******", password="******")
def handle(self, *args, **options): number_to_create: int = options['threads'] fake: Generator = Factory.create( getattr(settings, 'FAKER_LOCALE', None)) users = User.objects.all() categories = Category.objects.filter(lft=F('rght') - 1) for _ in tqdm(range(number_to_create), desc='Creating new threads'): title: str = fake.sentence(nb_words=20) weight: int = random.choices([ Thread.WEIGHT_DEFAULT, Thread.WEIGHT_PINNED_LOCALLY, Thread.WEIGHT_PINNED_GLOBALLY ], weights=[0.85, 0.1, 0.05])[0] is_unapproved: bool = random.choices([True, False], weights=[0.1, 0.9])[0] is_hidden: bool = random.choices([True, False], weights=[0.1, 0.9])[0] is_closed: bool = random.choices([True, False], weights=[0.1, 0.9])[0] category: Category = random.choice(categories) starter: User = random.choice(users) created_on: datetime = make_aware( fake.date_time_this_decade(before_now=True, after_now=False, tzinfo=None)) paragraphs: List[str] = [] for _ in range(random.randint(1, 20)): if random.random() < 0.1: width = random.randint(100, 1600) height = random.randint(100, 1600) url = UNSPLASH_URL % (width, height) paragraphs.append(f'<p><img src="{url}" alt="" /></p>') else: sentences = fake.sentences(random.randint(1, 20)) paragraph = ' '.join(sentences) paragraphs.append(f'<p>{paragraph}</p>') content = ''.join(paragraphs) Thread(title=title, content=content, weight=weight, is_unapproved=is_unapproved, is_hidden=is_hidden, is_closed=is_closed, category=category, starter=starter, created_on=created_on).save()
def launch(request): validate_request(request) tool_provider = initialize_lti_tool_provider(request) # collect anonymous_id and consumer key in order to fetch LTIProfile # if it exists, we initialize the tool otherwise, we create a new user user_id = get_lti_value('user_id', tool_provider) # user_id = "tempSessionID" request.session['anon_id'] = user_id # hash_anon_id(user_id) debug_printer('DEBUG - Found anonymous ID in request: %s' % user_id) course = get_lti_value(settings.LTI_COURSE_ID, tool_provider) request.session['course_id'] = course debug_printer('DEBUG - Found course being accessed: %s' % course) roles = get_lti_value('roles', tool_provider) is_instructor = False for role in roles: if role in settings.ADMIN_ROLES: is_instructor = True request.session['is_instructor'] = is_instructor debug_printer('DEBUG - Found is_instructor being accessed: %s' % is_instructor) custom_topic = get_lti_value('custom_topic', tool_provider) or "Current" #threads = Thread.getUnpinnedThreads(course_id=course, topic=custom_topic) #pinned_threads = Thread.getPinnedThreads(course_id=course, custom_topic) if is_instructor: threads = Thread.objects.filter(topic=custom_topic, course_id=course, pinned=False) pinned_threads = Thread.objects.filter(topic=custom_topic, course_id=course, pinned=True) else: threads, pinned_threads = Thread.getSeparatedThreads( course, custom_topic) noPseudos = len(Pseudonym.getAllPseudonymsForCategory(course)) == 0 return render_main_thread( request, { 'threads': threads, 'is_instructor': is_instructor, 'pinned_threads': pinned_threads, 'current_topic': custom_topic, 'noPseudos': noPseudos })
def filter_topic(request, topic): if request.session['is_instructor']: threads = Thread.objects.filter(topic=topic, course_id=request.session['course_id'], pinned=False) pinned_threads = Thread.objects.filter( topic=topic, course_id=request.session['course_id'], pinned=True) else: threads, pinned_threads = Thread.getSeparatedThreads( request.session['course_id'], topic) return render_main_thread( request, { "threads": threads, "pinned_threads": pinned_threads, 'is_instructor': request.session['is_instructor'], 'current_topic': topic })
def test(request): request.session['anon_id'] = 'test' request.session['course_id'] = 'testSession' request.session['is_instructor'] = True users = Post.objects.all().order_by('anon_id').distinct( 'anon_id').values_list('anon_id') context = {} context.update({ 'threads': Thread.objects.filter(pinned=False), 'pinned_threads': Thread.objects.filter(pinned=True), 'topics': Thread.getTopics(None), 'is_instructor': True, 'current_topic': "Current", 'noPseudos': [], 'mentioned_id': "test", 'notifications': [], 'users': users, 'usersCount': len(users) }) return render(request, 'lti/test.html', context)
def statistics(request): if not request.session['is_instructor']: return PermissionDenied course = request.session['course_id'] topics = Thread.getTopics(course) data = dict() threads_dates = [0, 0, 0, 0, 0, 0, 0] replies_dates = [0, 0, 0, 0, 0, 0, 0] replies_times = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] total_replies = 0 total_threads = 0 total_message_length = 0 total_unique_users = Set([]) for topic in topics: topic_name = topic[0] topic_threads = Thread.objects.filter(course_id=course, topic=topic_name) for day in range(7): threads_dates[day] = threads_dates[day] + len( topic_threads.filter(latest_reply__week_day=day + 1)) total_replies = 0 total_threads += len(topic_threads) unique_users = Set([]) thread_stats = [] for thread in topic_threads: replies = thread.post_set.all() total_replies += len(replies) thread_unique_users = Set([]) uid_num_posts = { '1': 0, '2': 0, '3': 0, '4': 0, '5to10': 0, 'gt10': 0 } for day in range(7): replies_dates[day] = replies_dates[day] + len( replies.filter(updated_date__week_day=day + 1)) for time in range(24): replies_times[time] = replies_times[time] + len( replies.filter(updated_date__hour=time)) for reply in replies: thread_unique_users.add(reply.anon_id) unique_users.add(reply.anon_id) total_replies += 1 total_message_length += len(reply.message) for uid in thread_unique_users: num_of_replies = len(replies.filter(anon_id=uid)) if num_of_replies >= 5: if num_of_replies > 10: uid_num_posts['gt10'] = uid_num_posts['gt10'] + 1 else: uid_num_posts['5to10'] = uid_num_posts['5to10'] + 1 else: uid_num_posts[unicode(num_of_replies)] = uid_num_posts[ unicode(num_of_replies)] + 1 thread_stats.append({ 'pk': thread.pk, 'thread_name': thread.title, 'unique_users': len(thread_unique_users), 'replies_num': len(replies), 'uid_replies': uid_num_posts }) total_unique_users = total_unique_users.union(unique_users) data.update({ topic_name: { 'threads_num': len(topic_threads), 'replies_num': total_replies, 'unique_users': len(unique_users), 'thread_stats': thread_stats } }) if total_replies == 0: total_replies = 1 context = { 'stats': data, 'stats_json': json.dumps(data), 'threads_dates': threads_dates, 'replies_dates': replies_dates, 'replies_times': replies_times, 'average_length': total_message_length / total_replies, 'replies_count': total_replies, 'threads_count': total_threads, 'uniques_count': len(total_unique_users) } return render(request, 'lti/stats.html', context)
class VerifyThread(TestCase): def setUp(self): self.u = User.objects.create_user(username="******", password="******") self.profile = UserProfile.objects.get(user=self.u) self.thread = Thread(owner=self.profile, subject="Default Thread Test") self.thread.save() self.message = Message(owner=self.profile, body="Default Reply Test", thread=self.thread) self.message.save() self.client.login(username="******", password="******") def test_thread_created(self): self.assertEqual(1, Thread.objects.all().count()) self.assertEqual(self.thread, Thread.objects.get(pk=self.thread.pk)) self.assertEqual(1, Thread.objects.filter(subject=self.thread.subject).count()) self.assertEqual(0, Thread.objects.filter(subject="Tabboo").count()) def test_thread_created(self): urls = [ "/", "/threads/", "/threads/{0}/".format(self.thread.pk), "/threads/all/", "/threads/list/", "/profile/{0}/threads/".format(self.u.username), "/profile/{0}/messages/".format(self.u.username), ] for url in urls: response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, self.thread.subject) self.assertNotContains(response, MESSAGES['MESSAGE_ERROR']) def test_create_thread(self): urls = [ "/threads/", "/threads/all/", ] subject = "Thread Subject Test" body = "Thread Body Test" for url in urls: response = self.client.post(url, { "submit_thread_form": "", "subject": subject, "body": body, }, follow=True) self.assertRedirects(response, url) self.assertContains(response, subject) self.assertContains(response, body) thread = Thread.objects.get(subject=subject) self.assertNotEqual(thread, None) self.assertEqual(Message.objects.filter(thread=thread).count(), 1) self.assertEqual(Message.objects.get(thread=thread).body, body) thread.delete() def test_bad_thread(self): urls = [ "/threads/", "/threads/all/", ] subject = "Thread Subject Test" body = "Thread Body Test" for url in urls: response = self.client.post(url, { "submit_thread_form": "", "subject": subject, }) self.assertEqual(response.status_code, 200) self.assertContains(response, MESSAGES['THREAD_ERROR']) self.assertEqual(Thread.objects.filter().count(), 1) try: thread = Thread.objects.get(subject=subject) except Thread.DoesNotExist: pass else: self.assertEqual(thread, None) def test_post_reply(self): urls = [ "/threads/", "/threads/{0}/".format(self.thread.pk), "/threads/all/", ] body = "Reply Body Test" for url in urls: response = self.client.post(url, { "submit_message_form": "", "thread_pk": self.thread.pk, "body": body, }, follow=True) self.assertRedirects(response, url) self.assertContains(response, body) thread = Thread.objects.get(pk=self.thread.pk) self.assertNotEqual(thread, None) self.assertEqual(Message.objects.filter(thread=thread).count(), 2) message = Message.objects.get(thread=thread, body=body) self.assertNotEqual(message, None) message.delete() def test_bad_reply(self): urls = [ "/threads/", "/threads/{0}/".format(self.thread.pk), "/threads/all/", ] body = "Reply Body Test" for url in urls: response = self.client.post(url, { "submit_message_form": "", "thread_pk": "a{0}".format(self.thread.pk), "body": body, }) self.assertEqual(response.status_code, 200) self.assertContains(response, MESSAGES['MESSAGE_ERROR']) thread = Thread.objects.get(pk=self.thread.pk) self.assertNotEqual(thread, None) self.assertEqual(Message.objects.filter(thread=thread).count(), 1) try: message = Message.objects.get(thread=thread, body=body) except Message.DoesNotExist: pass else: self.assertEqual(message, None)