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
def new_topic(request): user = request.user if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): category = form.cleaned_data['category'] topic = Topic(title=form.cleaned_data['title'], author=user, category=category ) topic.save() first_post = Post(topic=topic, author=user, date_published=topic.date_published, content=form.cleaned_data['content']) first_post.save() return HttpResponseRedirect(topic.get_absolute_url()) else: form = NewTopicForm() return render(request, 'xadmin/new_topic.html', { 'form': form })
def topic_create(request, slug): ''' 发表新帖子 ''' node = get_object_or_404(Node, slug=slug) form = CreateForm() if request.method == "POST": form = CreateForm(request.POST) if form.is_valid(): user = request.user topic = Topic(title=form.cleaned_data['title'], content=form.cleaned_data['content'], created=timezone.now(), node=node, author=user, reply_count=0, last_touched=timezone.now()) topic.save() return redirect(reverse('forum:index')) user = request.user # 发帖查重 if request.user.is_authenticated(): counter, notifications_count = user_info(request.user) active_page = 'topic' node_slug = node.slug update_reputation(user.id, -5) return render(request, 'topic/create.html', locals())
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()
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})
def import_topics(self): print "* Importing topics" rows = self._query("select * from smf_topics") for row in rows: topic = Topic( id=row['ID_TOPIC'], is_sticky=row['isSticky'], board=Board.objects.get(id=row['ID_BOARD'])) disable_auto_now(topic) topic.save()
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, }, )
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, }, )
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()
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 })
def showtopic(request, gurl_number, turl_number): group = Group.objects(url_number=gurl_number).get() topic = Topic.objects(url_number=turl_number).get() topic.clicks += 1 topic.save() if request.method == "POST": form = NewPostForm(request.POST) if form.is_valid(): content = form.cleaned_data["content"] post = Post(content=content) post.author = request.user post.creat_time = datetime.datetime.now() post.floor = Post.objects(topic=topic).count() + 1 post.topic = topic post.is_active = True post.save() topic.update_author = request.user topic.update_time = datetime.datetime.now() topic.save() return HttpResponseRedirect("/group/" + str(gurl_number) + "/topic/" + str(turl_number) + "/") else: form = NewPostForm() return render_to_response( "group/group_topic.html", {"group": group, "current_user": request.user, "form": form, "topic": topic, "STATIC_URL": STATIC_URL}, context_instance=RequestContext(request), )
def save(self): topic_post = False if not self.topic: topic = Topic(forum=self.forum, posted_by=self.user, subject=self.cleaned_data['subject']) topic_post = True topic.save() else: topic = self.topic post = Post(topic=topic, posted_by=self.user, poster_ip=self.ip, message=self.cleaned_data['message'], topic_post=topic_post) post.save() attachments = self.cleaned_data['attachments'] post.update_attachments(attachments) return post
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)
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
def global_variables(request): return { 'hot_nodes': Node.hot(), 'hot_topics': Topic.hot(), 'hot_users': User.hot(), 'latest_topics': Topic.objects.order_by('-id')[:10], 'central_banks': CentralBank.objects.all(), }
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
def save(self, commit=True): if not self.topic: # if this post create new topic, create this corresponding topic topic = Topic(forum=self.forum, title=escape(self.cleaned_data['title']), created_by=self.user, updated_by=self.user) topic.save() self.topic = topic topic_post = True else: topic = self.topic topic_post = False post = Post(topic=topic, created_by=self.user, updated_by=self.user, topic_post=topic_post, content=self.cleaned_data['content'], reply_on=self.parent) post.topic = topic if commit: post.save() if topic_post: topic.post = post topic.content = post.content topic.save() return post
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] + '...')
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)
def add_topic(request): t1 = Topic (topic_cat_id= request.POST['category'], topic_by_id=request.user.id, topic_date=timezone.now(), topic_name=request.POST['topic_name'],topic_desc=request.POST['topic_desc'], topic_views='0', topic_stars='0', topic_active='0') t1.save() if not request.user in t1.topic_subscribers.all(): t1.topic_subscribers.add(request.user) # Topic subscriptions t1.subscribes += 1 t1.save() ###content = "New topic Posted : "+ t1.topic_name +" by -"+ str(request.user) url = "http://test.archilane.com/forum/topic/" + str(t1.id) topic_subscribers = t1.topic_subscribers.all() module = 'add_topic' key = t1.pk Notification.save_notification(module, key, url,'forum','Topic','private',topic_subscribers) if t1.topic_cat.subscribes > 0: cat_subscribers = t1.topic_cat.cat_subscribers.all() Notification.save_notification(module, key, url,'forum','Category','private',cat_subscribers) return HttpResponse(t1.pk)
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('/')
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('/')
def get_context_data(self, **kwargs): ctx = { 'hot_topics': Topic.hot(), 'hot_nodes': Node.hot(), 'total_users': User.objects.count(), 'total_topics': User.objects.count(), 'total_nodes': Node.objects.count(), 'total_replies': Reply.objects.count(), 'planes': Plane.objects.all(), 'tab': 'forum', } return ctx
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)
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()
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)
def save(self): # Create the new topic new_topic = Topic(forum=self.topic.forum, name=self.cleaned_data["name"]) new_topic.save() # Move posts to the new topic self.topic.posts.filter(pk__in=self.cleaned_data["posts"]).update(topic=new_topic) # Update the new topic stats new_topic.first_post = new_topic.posts.order_by("date")[0] new_topic.update_posts_count() new_topic.update_last_post() new_topic.save() # Update the old topic stats self.topic.first_post = self.topic.posts.order_by("date")[0] self.topic.update_posts_count() self.topic.update_last_post() self.topic.save() # Inform subscribed users about the new topic inform_new_topic(new_topic) return new_topic
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})
def index(request): hot_topics = Topic.hot() new_topics = Topic.objects.order_by('-id')[:10] recent_blogs = Blog.recent(5) stick_blogs = Blog.sticks() hot_blogs = Blog.hot(2) hot_nodes = Node.hot() return render(request, 'common/index.html', { 'hot': hot_topics, 'new': new_topics, 'recent_blogs': recent_blogs, 'hot_blogs': hot_blogs, 'sticks': stick_blogs, 'hot_nodes': hot_nodes, 'recent_events': EconomicEvent.objects.order_by('-time')[:10], 'tab': 'index', })
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))
def dashboard(request): user = request.user ranking_data = get_users_with_bigger_score() # getting the last 5 topics created new_topics_data = Topic.new_topics() # getting the last 5 exercises created new_exercises_data = Exercise.new_exercises() user_last_exercises = get_user_exercises_last_submissions(user) return render( request, 'dashboard.html', { 'data': ranking_data, 'topics': new_topics_data, 'exercises': new_exercises_data, 'user_exercises': user_last_exercises })
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)
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()
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-detail', args=(forum_id, ))) return render_to_response('django_simple_forum/new-topic.html', { 'form': form, 'forum': forum, }, context_instance=RequestContext(request))
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))
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')
def group(request, gurl_number): group = Group.objects(url_number=gurl_number).get() if request.method == "POST": form = NewTopicForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] topic = Topic(title=title) turl_number = len(Topic.objects) + 1 topic.url_number = turl_number topic.content = content topic.creat_time = datetime.datetime.now() topic.is_active = True topic.is_locked = False topic.is_top = False topic.clicks = 0 topic.update_time = datetime.datetime.now() topic.update_author = request.user sgcard = S_G_Card.objects(user=request.user, group=group).get() topic.creator = sgcard topic.save() return HttpResponseRedirect("/group/" + str(gurl_number) + "/topic/" + str(turl_number) + "/") else: form = NewTopicForm() return render_to_response( "group/group.html", {"form": form, "group": group, "STATIC_URL": STATIC_URL, "current_user": request.user}, context_instance=RequestContext(request), )
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/')
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)
def get_inactive_topic_list(self): from accounts.models import S_G_Card creator = S_G_Card.objects(group=self).all() from forum.models import Topic return Topic.objects(creator__in=creator, is_active=False)
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)
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()
def grouptopics(self):#我关注的小组的话题 from forum.models import Topic return Topic.objects(creator__in=S_G_Card.objects(group__in=self.get_sgcard().scalar('group')))
def add_topic(request): t1 = Topic (topic_cat_id= request.POST['category'], topic_by_id=request.user.id, topic_date=datetime.datetime.now(),#timezone.now(), topic_name=request.POST['topic_name'],topic_desc=request.POST['topic_desc'], topic_views='0', topic_stars='0', topic_active='0') t1.save() return HttpResponseRedirect("/forum/topic/%d" % t1.id)
def get_inactive_topic_list(self):#得到删除主题列表 from accounts.models import S_C_Card creator = S_C_Card.objects(corporation=self).all() from forum.models import Topic return Topic.objects(creator__in=creator,is_active=False)
def grouptopics_creat(self):#我创建的话题 from forum.models import Topic return Topic.objects(creator__in=S_G_Card.objects(user=self))
def create_topic(request): """ desc: Create a new topic params: str topic_title, post_text, int tag_id return: bool success, int topic_id, str topic_title, str topic_author """ response = { 'success': False, 'topic_id': -1, 'topic_title': '', 'topic_author': '', 'topic_date': '', } # Validate input if valid_request(request): topic_title = request.POST['topic_title'] tag_id = request.POST['tag_id'] post_text = request.POST['post_text'] date = timezone.now() if topic_title and tag_id and post_text: tag = Tag.objects.get(pk=tag_id) new_topic = Topic( title=topic_title, author=request.user, post_date=date, last_post=date ) new_topic.save() tag_topic = TagTopic.objects.create( tag=tag, topic=new_topic, date_added=date ) tag_topic.save() new_post = Post( text=post_text, author=request.user, post_date=date ) new_post.save() topic_post = TopicPost.objects.create( topic=new_topic, post=new_post, date_added=date ) # Set the response response['topic_id'] = new_topic.id response['topic_title'] = new_topic.title response['topic_author'] = new_topic.author.username response['topic_date'] = date # Everything was successful! response['success'] = True # Return results return JsonResponse(response)
def get_topic_list(self): # 得到论坛主题列表 from accounts.models import S_C_Card creator = S_C_Card.objects(corporation=self).all() from forum.models import Topic return Topic.objects(creator__in=creator)
def save(self, user): newTopic = Topic(title=self.cleaned_data['title'], description=self.cleaned_data['description'], pub_date=timezone.now(), creator=user) newTopic.save() return newTopic
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)
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))
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)
def test_return(self): comment = Comment(text='ddd', topic=Topic(text='t')) self.assertEqual(comment.__str__(), 'ddd')
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))