Пример #1
0
def new_topic(request, forum_id):
    form = TopicForm()
    forum = get_object_or_404(Forum, pk=forum_id)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = form.cleaned_data['description']
            topic.forum = forum
            topic.creator = request.user

            topic.save()

            return HttpResponseRedirect(
                reverse('forum:forum-detail', args=(forum_id, )))

    return render(
        request,
        'forum/new-topic.html',
        {
            'form': form,
            'forum': forum,
        },
    )
Пример #2
0
def add_topic(request, forum, section, preview):
    if not request.user.has_perm('forum.add_topic'):
        raise Http404()

    f = get_object_or_404(Forum, address=forum)
    s, ss = None, None
    try:
        s = f.section_set.get(address=section)
    except ObjectDoesNotExist:
        ss = get_object_or_404(Sub_section, address=section)
        s = ss.section

    if request.method == 'POST':
        errors = {'title': False, 'body': False}

        title = request.POST['input_title']
        if len(title) > 64:
            errors['title'] = True

        body = request.POST['input_body']
        if len(body) > 1000:
            errors['body'] = True

        if not True in errors.values():
            if not preview:
                try:
                    t = create_and_get_topic(title=title,
                                             creator=request.user,
                                             section=s if ss is None else ss,
                                             body=body)
                except ValueError:
                    # soon(30.08.12, 12:42)
                    # FIXME
                    # Обработать нормально эту ситуацию
                    raise Http404()
                return redirect(t.get_absolute_url())
            else:
                t = Topic(
                    title=title,
                    creator=request.user,
                    section=s,
                    sub_section=ss,
                )
                p = Post(creator=t.creator, topic=t, body=body)
                return direct_to_template(request, 'forum/add_topic.hdt', {
                    'topic': t,
                    'post': p,
                    'forum': f,
                    'section': s
                })
        return direct_to_template(request, 'forum/add_topic.hdt', {
            'topic_title': title,
            'post_body': text_block,
            'errors': errors
        })
    else:
        return direct_to_template(request, 'forum/add_topic.hdt', {
            'forum': f,
            'section': s if ss is None else ss
        })
Пример #3
0
def new_topic(request, slug):
    form = TopicForm()
    forum = get_object_or_404(Forum, slug=slug)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = ''
            topic.creator = request.user
            topic.save()

            topic.forums.add(forum)
            topic.save()

            post = Post()
            post.title = form.cleaned_data['title']
            post.body = form.cleaned_data['description']
            post.creator = request.user
            post.user_ip = request.META['REMOTE_ADDR']
            post.topic = topic
            post.save()
            return HttpResponseRedirect(reverse('topic-detail', args=(slug, topic.id, )))

    return render(request, 'forum/new-topic.html', {'form': form, 'forum': forum})
Пример #4
0
def question_topic(request):
    form = TopicForm2()

    if request.method == 'POST':
        form = TopicForm2(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = form.cleaned_data['description']
            topic.forum = form.cleaned_data['forum']
            topic.creator = request.user

            topic.save()

            return HttpResponseRedirect(reverse('forum:forum-index'))

    return render(
        request,
        'forum/question-topic.html',
        {
            'form': form,
        },
    )
Пример #5
0
def c2f(modeladmin, request, queryset):
    tid = 300
    pid = 1200
    for a in queryset:
        if a.subject == u'1':
            parser = html2txt()
            parser.feed(a.content)
            parser.close()
            message = parser.txt
            forum_id = 8
            subject = '%s' % (a.title)
            last_reply_on = a.time
            posted_by_id = a.name.id
            poster_ip = '1.1.1.1'
            created_on = a.time

            t = Topic(id = tid, forum_id = forum_id, posted_by_id = posted_by_id,\
                subject = subject, post_id = pid, created_on = created_on, last_reply_on = last_reply_on)
            t.save()

            p = Post(id=pid,
                     topic_id=tid,
                     posted_by_id=posted_by_id,
                     poster_ip=poster_ip,
                     topic_post=True,
                     message=message,
                     created_on=created_on)
            p.save()

            tid += 1
            pid += 1
Пример #6
0
    def post(self, request, *args, **kwargs):
        data = self.get_context_data()
        form = data["form"]

        # 发表权限控制才用
        # if not self.request.user.profile.can_create_topic():
        #     return super(CreateTopicView, self).render_to_response(data)

        if form.is_valid():
            title = form.cleaned_data['title']
            md = form.cleaned_data['content']
            node = form.cleaned_data['node']
            rendered = render_markdown(md)
            abstract = Truncator(strip_tags(rendered)).chars(60)

            if node.is_trash:
                rank = 0
            else:
                rank = 10
            topic = Topic(node=node, author=request.user, title=title,
                          markdown=md, content=rendered, abstract=abstract, rank=rank)
            mentioned = get_metioned_user(request.user, md)

            self._commit_changes(topic, mentioned)

            return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': topic.id}))

        return super(CreateTopicView, self).render_to_response(data)
Пример #7
0
    def save(self, commit=True):
        if not self.topic:
            # if this post create new topic, create this corresponding topic
            topic = Topic(
                forum=self.forum,
                created_by=self.user,
                title=self.cleaned_data['title'],
            )
            topic.save()
            self.topic = topic
        else:
            topic = self.topic

        post = Post(topic=topic,
                    created_by=self.user,
                    topic_post=True,
                    content=self.cleaned_data['content'])
        post.topic = topic
        if commit:
            post.save()
            if self.topic_post:
                topic.post = post
                topic.save()

        return post
Пример #8
0
    def handle(self, *args, **options):
        username = options['user']
        user = User.objects.get(username=username)

        manager, _created = Group.objects.get_or_create(name="manager")
        manager.save()
        user.groups.add(manager)

        tmpnode = self._add_section(ForumSection)
        if tmpnode:
            about = Topic(node=tmpnode, author=user, title="about")
            about.save()
            privacy = Topic(node=tmpnode, author=user, title="privacy")
            privacy.save()
            credit = Topic(node=tmpnode, author=user, title="credit")
            credit.save()
            t = Topic(node=tmpnode, author=user, title="topic")
            t.save()
Пример #9
0
    def save(self, user):
        tittle = self.cleaned_data['title']
        content = self.cleaned_data['content']
        categories = self.cleaned_data['categories']
        topic = Topic(author=user,
                      title=tittle,
                      categories=categories,
                      content=content)

        topic.save()
Пример #10
0
    def test_topic_text_more_then_can(self):
        text_for_topic = 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'

        topic = Topic(text=text_for_topic, owner=None)

        self.assertEqual(topic.text, text_for_topic)
def new_topic():
    form = topic_form()
    if form.validate_on_submit():
        topic = Topic(header=form.header.data,
                      content=form.content.data,
                      author=current_user)
        db.session.add(topic)
        db.session.commit()
        return redirect("/")

    return render_template("create_topic.html", form=form)
Пример #12
0
    def test_comment_text_more_then_can(self):
        text_for_commen = 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' \
                         'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'

        comment = Comment(text=text_for_commen, topic=Topic(text='t'))

        self.assertEqual(comment.__str__(), text_for_commen[:50] + '...')
Пример #13
0
    def save(self, *args, **kwargs):
        try:
            Topic.objects.filter(id=self.forum_id.id).update(
                title=self.title, description=self.description)
        except:
            topic = Topic.objects.create(title=self.title,
                                         description=self.description,
                                         created_by=self.author,
                                         category=Category(pk=3))
            self.forum_id = Topic(pk=topic.id)

        super().save(*args, **kwargs)
Пример #14
0
	def save(self, user):
		newthread = DiscussionThread()
		# Create an entry for this topic if it does not exist.
		if (Topic.objects.filter(type=self.cleaned_data["topic"]).count() == 0):
			new_instance = Topic()
			new_instance.type = self.cleaned_data["topic"]
			new_instance.save()
		# Regardless, assign this topic to this thread.
		topic = Topic.objects.get(type=self.cleaned_data["topic"])
		newthread.posted_under = topic
		newthread.user = user
		newthread.title = self.cleaned_data["title"]
		newthread.paragraph = self.cleaned_data["paragraph"]
		newthread.save()
Пример #15
0
def new_topic(request, forum_id):
    form = TopicForm()
    forum = get_object_or_404(Forum, pk=forum_id)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = form.cleaned_data['description']
            topic.forum = forum
            topic.creator = request.user
            userToUpdate = UserProfile.objects.get(user=request.user)
            nCredits = userToUpdate.credits
            userToUpdate.credits = int(float(nCredits + 200))

            # TODO: Change status (if points+100>threshold -> status changes)
            # Alert? Maybe return to page with status update info for user.
            # Make Gold/Platinum distinction

            if nCredits + 200 >= GOLD_THRESHOLD:
                newStatus = "Gold"
                userToUpdate.status = newStatus
                userToUpdate.save()
                topic.save()
                return render_to_response(
                    "forum/status_change.html", {'status': newStatus},
                    context_instance=RequestContext(request))
            elif nCredits + 100 >= PLATINUM_THRESHOLD:
                newStatus = "Platinum"
                userToUpdate.status = newStatus
                userToUpdate.save()
                topic.save()
                return render_to_response(
                    "forum/status_change.html", {'status': newStatus},
                    context_instance=RequestContext(request))
            else:
                userToUpdate.save()
                topic.save()
                return HttpResponseRedirect(
                    reverse('forum-detail', args=(forum_id, )))

    return render_to_response('forum/new-topic.html', {
        'form': form,
        'forum': forum,
    },
                              context_instance=RequestContext(request))
Пример #16
0
class TestTopicCreation(TestCase):
    topic = Topic()
    user = User()

    def setUp(self):
        self.topic.title = 'Basic Topic'
        self.topic.subtitle = 'How test in Django'
        self.user.email = "*****@*****.**"
        self.user.first_name = "TestUser"
        self.user.username = "******"
        self.user.is_active = True
        self.topic.description = '<p>Text Basic Exercise.</p>'
        self.user.save()

    def test_str_is_correct(self):
        self.topic.author = self.user
        self.topic.save()
        topic_database = Topic.objects.get(id=self.topic.id)
        self.assertEqual(str(topic_database), str(self.topic))

    def test_if_topic_is_saved_database(self):
        self.topic.author = self.user
        self.topic.save()
        topic_database = Topic.objects.get(id=self.topic.id)
        self.assertEqual(topic_database, self.topic)

    def test_topic_get_title(self):
        self.topic.author = self.user
        self.topic.save()
        topic_database = Topic.objects.get(id=self.topic.id)
        self.assertEqual(topic_database.title, self.topic.title)

    def test_topic_get_subtitle(self):
        self.topic.author = self.user
        self.topic.save()
        topic_database = Topic.objects.get(id=self.topic.id)
        self.assertEqual(topic_database.subtitle, self.topic.subtitle)

    def test_topic_get_author(self):
        self.topic.author = self.user
        self.topic.save()
        topic_database = Topic.objects.get(id=self.topic.id)
        self.assertEqual(str(topic_database.author), str(self.topic.author))

    def test_topic_get_description(self):
        self.topic.author = self.user
        self.topic.save()
        topic_database = Topic.objects.get(id=self.topic.id)
        self.assertEqual(topic_database.description, self.topic.description)
Пример #17
0
    def _on_publish_topic_sql(self, title, content, users):
        """
        发表主题时的数据库处理程序,sql后端
        :param title: 标题
        :param content: 内容
        :param users: 已验证的用户对象
        :return: 成功返回真,失败返回假
        """

        assert title != '' and content != '' and len(users) > 1 and isinstance(
            users[1], User)

        new_topic = Topic(title=title, content=content, author=users[1])
        new_topic.save()

        result = User.objects.filter(id=users[1].id).update(inc__topic_num=1)
        return result is not None
Пример #18
0
 def handle(*args, **options):
     url = "https://api.nytimes.com/svc/mostpopular/v2/viewed/7.json?api-key=" + nyt_api_key
     r = requests.get(url)
     data = json.loads(r.text) 
     topics = data['results']
     print(len(topics))
     i = 0
     for item in topics:
         print(str(round(i/len(topics)*100,2))+'%')
         i += 1
         if not Topic.objects.filter(title=item['title']).exists():
             topic = Topic()
             topic.title = item['title']
             topic.url = item['url']
             topic.published_date = datetime.datetime.strptime(item['published_date'], '%Y-%m-%d')
             topic.byline = item['byline']
             topic.abstract = item['abstract']
             topic.save()
Пример #19
0
def generate_fake_topics(count=100):
    seed()
    user_count = db.session.query(func.count(User.id)).scalar()
    group_count = db.session.query(func.count(TopicGroup.id)).scalar()
    for i in range(count):
        u = User.query.offset(randint(0, user_count - 1)).first()
        if group_count:
            g = TopicGroup.query.offset(randint(0, group_count - 1)).first()
        else:
            g = None
        now = forgery_py.date.date(True)
        p = Topic(title=forgery_py.lorem_ipsum.title()[:128],
                  body=forgery_py.lorem_ipsum.sentences(randint(20, 40)),
                  created_at=now,
                  updated_at=now,
                  author=u,
                  group=g)
        db.session.add(p)
    db.session.commit()
Пример #20
0
def new_topic(request, forum_id):
    form = TopicForm()
    forum = get_object_or_404(Forum, pk=forum_id)
    user = request.user

    if forum.closed and not user.has_perm('forum.can_post_lock_forum'):
        return render(request, 'personal/basic.html',
                      {'content': ['This forum is locked.']})

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = bleach_clean(form.cleaned_data['description'])
            topic.forum = forum
            topic.creator = user

            topic.save()

            tpkPost = Post()
            tpkPost.topic = topic
            tpkPost.title = topic.title
            tpkPost.body = bleach_clean(form.cleaned_data['description'])
            tpkPost.creator = user
            tpkPost.user_ip = get_client_ip(request)

            tpkPost.save()

            return HttpResponseRedirect(
                reverse('topic-detail', args=(
                    topic.id,
                    topic.slug,
                )))

    return render_to_response('forum/new-topic.html', {
        'form': form,
        'forum': forum,
    },
                              context_instance=RequestContext(request))
Пример #21
0
def post_create(request, slug=None):
    node = get_object_or_404(Node, slug=slug)

    form = CreateForm(request.POST)
    if not form.is_valid():
        return get_create(request, slug=slug, errors=form.errors)

    user = request.user
    try:
        last_created = user.topic_author.all().order_by('-created')[0]
    except IndexError:
        last_created = None

    if last_created:  # 如果用户最后一篇的标题内容与提交的相同
        last_created_fingerprint = hashlib.sha1(last_created.title + \
            last_created.content + str(last_created.node_id)).hexdigest()
        new_created_fingerprint = hashlib.sha1(form.cleaned_data.get('title') + \
            form.cleaned_data.get('content') + str(node.id)).hexdigest()

        if last_created_fingerprint == new_created_fingerprint:
            errors = {'duplicated_topic': [u'帖子重复提交']}
            return get_create(request, slug=slug, errors=errors)

    now = timezone.now()
    topic = Topic(
        title=form.cleaned_data.get('title'),
        content=form.cleaned_data.get('content'),
        created=now,
        node=node,
        author=user,
        reply_count=0,
        last_touched=now,
    )
    topic.save()

    reputation = user.reputation or 0
    reputation = reputation - 5  # 每次发布话题扣除用户威望5点
    reputation = 0 if reputation < 0 else reputation
    ForumUser.objects.filter(pk=user.id).update(reputation=reputation)

    return redirect('/')
Пример #22
0
def new_topic(request, slug):
    form = TopicForm()
    forum = get_object_or_404(Forum, slug=slug)
    
    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():
            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = form.cleaned_data['description']
            topic.forum = forum
            topic.creator = request.user

            topic.save()

            return HttpResponseRedirect(reverse('forum:forum-detail', args=(forum.slug, )))

    context = get_base_context()
    context.update({'form': form, 'forum': forum})
    return render(request, 'forum/new-topic.html', context)
Пример #23
0
def main(request):
    if request.method == "POST":
        post = json.loads(request.body)
        if "newTopic" in post.keys():
            new_topic = post['newTopic']
            topic = Topic(name=new_topic)
            topic.save()
            topics = [{"id": x.pk,
                       "name": x.name}
                      for x in Topic.objects.all()]
            return HttpResponse(json.dumps(topics))
        # deleting topics, never actually implemented client side
        # probably will never implement this feature, as a design choice
        if "topicID" in post.keys():
            tID = post['topicID']
            try:
                Topic.objects.get(pk=tID).delete()
            except Exception:
                return HttpResponse("server Error")
            return HttpResponse("")
        # searching for posts by title
        # a more complex algorithm can be employed here, but nah. Maybe later
        name = post['postName']
        posts = [
            {"title": x.title,
             "id": x.id}
            for x in Post.objects.filter(title__contains=name)
        ]
        return HttpResponse(json.dumps(posts))
    # loads all topics when loading the forum page
    posts = [
        {"title": x.title,
         "id": x.id}
        for x in Post.objects.all()
    ]
    return render(request, "forum/forum.html", context={"posts": posts})
Пример #24
0
 def test_owner(self):
     user = User.objects.create(username='******')
     topic = Topic(owner=user, text='la', subject='ta')
     self.assertEqual(topic.owner.username, 'alfred')
     self.assertEqual(topic.__str__(), 'ta la')
Пример #25
0
    def test_return(self):
        comment = Comment(text='ddd', topic=Topic(text='t'))

        self.assertEqual(comment.__str__(), 'ddd')
Пример #26
0
 def test_topic(self):
     topic = Topic(text='dd', id=1)
     comment = Comment(topic=topic, text='fd')
     self.assertEqual(comment.topic, topic)
     topic.delete()
     self.assertNotEqual(comment, None)
Пример #27
0
class TestRequestTopic(TestCase):

    topic = Topic()
    user = User()

    def setUp(self):
        self.user.email = "*****@*****.**"
        self.user.first_name = "TestUser"
        self.user.username = "******"
        self.user.is_active = True
        self.user.set_password('userpassword')
        self.user.save()

        self.user_wrong = User()
        self.user_wrong.email = "*****@*****.**"
        self.user_wrong.first_name = "WrongUser"
        self.user_wrong.username = "******"
        self.user_wrong.is_active = True

        self.topic.title = 'Basic Topic'
        self.topic.subtitle = 'How test in Django'
        self.topic.author = self.user
        self.topic.description = '<p>Text Basic Exercise.</p>'
        self.topic.locked = False

        self.factory = RequestFactory()
        self.wrong_author = 'User'
        self.topic_creation_form = {
            'title': self.topic.title,
            'subtitle': self.topic.subtitle,
            'description': self.topic.description,
        }
        self.wrong_topic_creation_form = self.topic_creation_form

    def test_list_all_topics(self):
        request = self.factory.get('/forum/topics/')
        response = list_all_topics(request)
        self.assertEqual(response.status_code, REQUEST_SUCCEEDED)

    def test_show_topic(self):
        self.topic.save()
        request = self.factory.get('/forum/topics/1/')
        request.user = self.user
        response = show_topic(request, self.topic.id)
        self.assertEqual(response.status_code, REQUEST_SUCCEEDED)

    def test_show_topic_when_topic_is_not_deletable(self):
        self.topic.save()

        self.user_wrong.save()
        request = self.factory.get('/forum/topics/1/')
        request.user = self.user_wrong
        response = show_topic(request, self.topic.id)
        self.assertEqual(response.status_code, REQUEST_SUCCEEDED)

    # def test_show_topic_when_topic_is_not_deletable(self):
    #     self.topic.author.username = self.wrong_author.username
    #     self.topic.save()
    #     request = self.factory.get('/forum/topics/1/')
    #     request.user = self.user
    #     response = show_topic(request, self.topic.id)
    #     self.assertEqual(response.status_code, REQUEST_SUCCEEDED)

    def test_show_topic_if_topic_does_not_exit(self):
        request = self.factory.get('/forum/topics/1/')
        request.user = self.user
        response = show_topic(request, self.topic.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')

    def test_create_topic(self):
        request = self.factory.post('/forum/newtopic/',
                                    self.topic_creation_form)

        # This is necessary to test with messages.
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        request.user = self.user
        response = create_topic(request)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')

    def test_create_topic_with_invalid_form(self):
        self.wrong_topic_creation_form['title'] = ' '
        request = self.factory.post('/forum/newtopic/',
                                    self.wrong_topic_creation_form)
        request.user = self.user
        response = create_topic(request)
        self.assertEqual(response.status_code, REQUEST_SUCCEEDED)

    def test_if_user_can_delete_topic(self):
        self.topic.save()
        request = self.factory.get('/forum/deletetopic/1/', follow=True)
        request.user = self.user
        response = delete_topic(request, self.topic.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')

    def test_if_user_cant_delete_topic(self):
        self.topic.author.username = self.wrong_author
        self.topic.save()
        request = self.factory.get('/forum/deletetopic/1/', follow=True)
        request.user = self.user
        response = delete_topic(request, self.topic.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')

    def test_delete_topic_which_does_not_exit(self):
        request = self.factory.get('/forum/deletetopic/1/', follow=True)
        request.user = self.user
        response = delete_topic(request, self.topic.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')

    def test_show_lock_topic_button_when_topic_isnt_lockable(self):
        self.user_wrong.save()
        self.topic.save()
        lockable_topic = __show_lock_topic_button__(self.topic,
                                                    self.user_wrong)
        self.assertFalse(lockable_topic)

    def test_show_lock_topic_button_when_topic_is_lockable(self):
        self.topic.save()
        lockable_topic = __show_lock_topic_button__(self.topic, self.user)
        self.assertTrue(lockable_topic)

    def test_show_lock_topic_button_when_topic_is_already_locked(self):
        topic = self.topic
        topic.locked = True
        topic.save()
        lockable_topic = __show_lock_topic_button__(topic, self.user)
        self.assertFalse(lockable_topic, False)

    def test_show_lock_topic_button_when_topic_is_null(self):
        topic = None
        try:
            __show_lock_topic_button__(topic, self.user)
        except AssertionError:
            self.assertTrue(True)

    def test_show_lock_topic_button_when_user_is_null(self):
        self.topic.save()
        user = None
        try:
            __show_lock_topic_button__(self.topic, user)
        except AssertionError:
            self.assertTrue(True)

    def test_lock_topic_when_topic_is_lockable(self):
        self.topic.save()
        request = self.factory.get('/forum/locktopic/' + str(self.topic.id),
                                   follow=True)
        request.user = self.user
        response = lock_topic(request, self.topic.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')

        locked_topic = Topic.objects.get(id=self.topic.id)

        self.assertTrue(locked_topic.locked)

    def test_lock_topic_when_topic_doesnt_exist(self):
        request = self.factory.get('/forum/locktopic/' + str(self.topic.id),
                                   follow=True)
        request.user = self.user
        lock_topic(request, self.topic.id)
        self.assertRaises(ObjectDoesNotExist)

    def test_lock_topic_when_user_cant_lock(self):
        self.user_wrong.save()
        self.topic.save()
        request = self.factory.get('/forum/locktopic/' + str(self.topic.id),
                                   follow=True)
        request.user = self.user_wrong
        response = lock_topic(request, self.topic.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')

    def test_lock_topic_when_user_is_staff_lock(self):
        user = self.user_wrong
        user.is_staff = True
        user.save()
        self.topic.save()
        request = self.factory.get('/forum/locktopic/' + str(self.topic.id),
                                   follow=True)
        request.user = user
        response = lock_topic(request, self.topic.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')

        locked_topic = Topic.objects.get(id=self.topic.id)

        self.assertTrue(locked_topic.locked)
Пример #28
0
class TestAnswerTopic(TestCase):
    answer = Answer()
    topic = Topic()
    user = User()
    user_topic = User()

    def setUp(self):
        self.answer.description = "<p>Description answer.</p>"
        self.user.email = "*****@*****.**"
        self.user.first_name = "TestUser"
        self.user.username = "******"
        self.user.is_active = True
        self.user_topic.email = "*****@*****.**"
        self.user_topic.first_name = "TestUser"
        self.user_topic.username = "******"
        self.user_topic.is_active = True
        self.user_topic.save()
        self.topic.title = 'Basic Topic'
        self.topic.subtitle = 'How test in Django'
        self.topic.description = '<p>Text Basic Exercise.</p>'
        self.topic.author = self.user_topic
        self.factory = RequestFactory()
        self.user.set_password('userpassword')
        self.user.save()
        self.topic.save()
        self.wrong_user = '******'
        self.answer_creation_form = {
            'description': self.answer.description,
        }

    def test_answer_topic(self):
        request = self.factory.post('/forum/topics/1/',
                                    self.answer_creation_form)
        request.user = self.user
        response = show_topic(request, 1)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)

    def test_list_all_answer(self):
        list_answers = self.topic.answers()
        self.assertEqual(len(list_answers), 0)

    def list_all_answer_except_best_answer(self):
        self.answer.user = self.user
        self.answer.topic = self.topic
        self.answer.save()

        self.topic.best_answer = self.answer
        self.topic.save()

        list_answers = self.topic.answers()

        self.assertEqual(len(list_answers), 0)

    def test_if_user_can_delete_answer(self):
        self.answer.user = self.user
        self.answer.topic = self.topic
        self.answer.save()
        request = self.factory.get('/forum/deleteanswer/1/', follow=True)
        request.user = self.user
        response = delete_answer(request, self.answer.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/1/')

    def test_delete_answer_which_does_not_exit(self):
        self.answer.user = self.user
        self.answer.topic = self.topic
        self.answer.save()
        request = self.factory.get('/forum/deleteanswer/12/', follow=True)
        request.user = self.user
        response = delete_answer(request, 12)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)

    def test_if_user_cant_delete_answer(self):
        self.answer.user.username = self.wrong_user
        self.answer.topic = self.topic
        self.answer.save()
        request = self.factory.get('/forum/deleteanswer/1/', follow=True)
        request.user = self.user
        response = delete_answer(request, self.answer.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/1/')

    def test_if_user_can_see_delete_answer_button(self):
        self.answer.user = self.user
        self.answer.topic = self.topic
        self.answer.save()
        answers = Answer.objects.filter(topic=self.answer.topic)
        not_deletable_answer = []
        not_deletable_answer.append(True)
        deletable_answers = __show_delete_answer_button__(
            answers, self.topic, self.user.username)
        self.assertEqual(deletable_answers, not_deletable_answer)

    def test_if_user_cant_see_delete_answer_button(self):
        self.answer.user = self.user
        self.answer.topic = self.topic
        self.answer.save()
        answers = Answer.objects.filter(topic=self.topic)
        not_deletable_answer = []
        not_deletable_answer.append(False)
        deletable_answers = __show_delete_answer_button__(
            answers, self.topic, self.wrong_user)
        self.assertEqual(deletable_answers, not_deletable_answer)

    def test_if_user_can_see_choose_best_answer_button(self):
        topic_author = self.topic.author
        current_user = topic_author
        choose_best_answer = __show_choose_best_answer_button__(
            topic_author, current_user)
        self.assertEqual(choose_best_answer, True)

    def test_if_user_cant_see_choose_best_answer_button(self):
        topic_author = self.topic.author
        current_user = self.user
        choose_best_answer = __show_choose_best_answer_button__(
            topic_author, current_user)
        self.assertEqual(choose_best_answer, False)

    def test_if_topic_author_cant_choose_an_inexistent_answer(self):
        request = self.factory.get('/forum/best_answer/1/')
        request.user = self.user
        response = best_answer(request, self.answer.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/')

    def test_if_topic_author_can_choose_best_answer(self):
        self.answer.user = self.user
        self.answer.topic = self.topic
        self.answer.save()
        request = self.factory.get('/forum/best_answer/1/')
        request.user = self.topic.author
        response = best_answer(request, self.answer.id)
        self.assertEqual(response.status_code, REQUEST_REDIRECT)
        self.assertEqual(response.url, '/en/forum/topics/1/')
Пример #29
0
class TestAnswerCreation(TestCase):
    answer = Answer()
    topic = Topic()
    user = User()
    user_topic = User()

    def setUp(self):
        self.answer.description = "<p>Description answer.</p>"
        self.user.email = "*****@*****.**"
        self.user.first_name = "TestUser"
        self.user.username = "******"
        self.user.is_active = True
        self.user_topic.email = "*****@*****.**"
        self.user_topic.first_name = "TestUser"
        self.user_topic.username = "******"
        self.user_topic.is_active = True
        self.user_topic.save()
        self.topic.title = 'Basic Topic'
        self.topic.subtitle = 'How test in Django'
        self.topic.author = self.user_topic
        self.topic.description = '<p>Text Basic Exercise.</p>'
        self.user.set_password('userpassword')
        self.user.save()
        self.topic.save()

    def test_if_answer_is_saved_database(self):
        self.answer.user = self.user
        self.answer.topic = self.topic
        self.answer.save()
        answer_database = Answer.objects.get(id=self.answer.id)
        self.assertEqual(str(answer_database), str(self.answer))

    def test_if_creates_answer(self):
        self.answer.creates_answer(self.user, self.topic,
                                   self.answer.description)
        answer_database = Answer.objects.get(id=self.answer.id)
        self.assertEqual(str(answer_database), str(self.answer))

    def test_answer_get_description(self):
        self.answer.creates_answer(self.user, self.topic,
                                   self.answer.description)
        answer_database = Answer.objects.get(id=self.answer.id)
        self.assertEqual(answer_database.description, self.answer.description)

    def test_answer_get_date(self):
        self.answer.creates_answer(self.user, self.topic,
                                   self.answer.description)
        answer_database = Answer.objects.get(id=self.answer.id)
        self.assertEqual(answer_database.date_answer, self.answer.date_answer)

    def test_answer_get_user(self):
        self.answer.creates_answer(self.user, self.topic,
                                   self.answer.description)
        answer_database = Answer.objects.get(id=self.answer.id)
        self.assertEqual(answer_database.user, self.answer.user)

    def test_answer_get_topic(self):
        self.answer.creates_answer(self.user, self.topic,
                                   self.answer.description)
        answer_database = Answer.objects.get(id=self.answer.id)
        self.assertEqual(answer_database.topic, self.answer.topic)
Пример #30
0
    def post(self, request):
        test = YouTubeTranscriptApi.get_transcript("R9rLCPW-eUI", languages=['id', 'en'])

        employee = Employee.objects.get(user=request.user)
        try:
            with transaction.atomic():
                if employee.status == 0:
                    raise PermissionDenied("user is not admin")

                courseName = request.data['course']['name']
                category = request.data['course']['category']
                img = request.data['course']['img']
                description = request.data['course']['description']
                price = request.data['course']["price"]
                learningPoint = request.data['course']["sylabus"]
                estimateTime = datetime.strptime(request.data['course']["estimate_time"], '%H:%M:%S')

                categoryObject = Topic.objects.filter(topic=category)
                if len(category) == 0 :
                    categoryObject = Topic(topic=category)
                else :
                    categoryObject = Topic.objects.filter(topic=category)

                course = Course(name=courseName, img=img, price =price, description=description, learningPoint=learningPoint, estimateTime=estimateTime)
                course.save()

                for i in categoryObject :
                    course.topic.add(i)


                
                for i in request.data['course']['section'] :
                    sectionTitle = i['title']
                    sectionDescription = i['description']
                    section = Section(title=sectionTitle, description=sectionDescription)
                    section.save()
                    course.section.add(section)

                    for j in i['lesson'] :
                        lessonTitle = j["title"]
                        lesson = Lesson(title=lessonTitle)
                        lesson.save()

                        allStep = []

                        for k in j["step"] :
                            stepTitle = k["title"]
                            stepType = k['type']

                            
                            if stepType == 0 :
                                stepContentText = k["content_text"]
                                stepTimeMinimum = datetime.strptime(k['time_minimum'], '%H:%M:%S')
                                step = Step(title=stepTitle, type=stepType, contentText=stepContentText, timeMinimum=stepTimeMinimum)
                                step.save()
                                allStep.append(step)
                            elif stepType == 1 :
                                stepContentVideo = k["content_video"]
                                stepTimeMinimum = datetime.strptime(k['time_minimum'], '%H:%M:%S')
                                step = Step(title=stepTitle, type=stepType, contentText=stepContentVideo,timeMinimum=stepTimeMinimum)
                                step.save()
                                allStep.append(step)


                        for k in range(len(allStep)) :
                            if len(allStep) == 1 :
                                continue
                            elif k == 0 :
                                allStep[k].nextID = allStep[k+1]
                                allStep[k].save()
                            elif k == (len(allStep) -1)  :
                                allStep[k].prevID = allStep[k - 1]
                                allStep[k].save()
                            else :
                                allStep[k].prevID = allStep[k - 1]
                                allStep[k].nextID = allStep[k+1]
                                allStep[k].save()

                        for k in allStep :
                            lesson.step.add(k)
                            course.totalStepAndQuiz += 1

                        section.lesson.add(lesson)

                    quizTitle = i['quiz']["title"]
                    quizDescription = i['quiz']["description"]
                    quizMinimumScore = i['quiz']["minimum_score"]
                    quizSection = QuizSection(title=quizTitle,
                                              description=quizDescription,
                                              minimumQuizScore=quizMinimumScore
                                              )
                    quizSection.save()
                    section.quizSection = quizSection
                    section.save()

                    for k in i['quiz']["quiz"] :
                        question = k["question"]
                        point = k['point']
                        quizChoice1Object = Choice(choice= k['choice_1']['choice'],
                                                   isRight= True if k['choice_1']["is_right"] == "true" else False )
                        quizChoice2Object = Choice(choice=k['choice_2']['choice'],
                                                   isRight=True if k['choice_2']["is_right"] == "true" else False)
                        quizChoice3Object = Choice(choice=k['choice_3']['choice'],
                                                   isRight=True if k['choice_3']["is_right"] == "true" else False)

                        quizChoice4Object = Choice(choice=k['choice_4']['choice'],
                                                   isRight=True if k['choice_4']["is_right"] == "true" else False)

                        quizChoice1Object.save()
                        quizChoice2Object.save()
                        quizChoice3Object.save()
                        quizChoice4Object.save()

                        quizObject = Quiz(question=question, choice1= quizChoice1Object, choice2=quizChoice2Object, choice3=quizChoice3Object, choice4=quizChoice4Object, point=point)
                        quizObject.save()
                        quizSection.quiz.add(quizObject)
                        course.totalStepAndQuiz += 1

                    course.section.add(section)
                    course.save()
                return Response({
                    "status" : 201,
                    "message" : "success",
                }, status=status.HTTP_201_CREATED)



        except PermissionDenied as e :
            return PermissionDeniedHandler(e)