def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver(executable_path='vendor/chromedriver') cls.selenium.implicitly_wait(0.5) thread_title_json = { "object": "value", "document": { "object": "document", "data": {}, "nodes": [ { "object": "block", "type": "paragraph", "data": {}, "nodes": [ { "object": "text", "text": "Thread0", "marks": [] } ] } ] } } # data setup cls.forum = Forum.objects.create(title="Forum0", description="Automatically generated forum.") cls.thread = Thread.objects.create(title=json.dumps(thread_title_json), author=None, forum=cls.forum) # Make dummy thread OP to keep thread invariant (every thread must have at least 1 post) p = Post(content="This is the OP.", thread = cls.thread); p.save();
def newthread(request, forum): """ Rudimentary post function - this should probably use newforms, although not sure how that goes when we're updating two models. Only allows a user to post if they're logged in. """ if not request.user.is_authenticated(): return HttpResponseRedirect("%s?next=%s" % (LOGIN_URL, request.path)) f = get_object_or_404(Forum, slug=forum) if not Forum.objects.has_access(f, request.user.groups.all()): return HttpResponseForbidden() if request.method == "POST": form = CreateThreadForm(request.POST) if form.is_valid(): t = Thread(forum=f, title=form.cleaned_data["title"]) t.save() p = Post(thread=t, author=request.user, body=form.cleaned_data["body"], time=datetime.now()) p.save() return HttpResponseRedirect(t.get_absolute_url()) else: form = CreateThreadForm() return render_to_response("forum/newthread.html", RequestContext(request, {"form": form, "forum": f}))
def reply(request, thread): """ 回复帖子子 条件: 1、帖子允许回复,没有关闭 2、当前用户登录 """ t = get_object_or_404(Thread, pk=thread) if t.closed: return Http404 if not Forum.objects.has_access(t.forum, request.user.groups.all()): return Http404 if request.method == "POST": form = ReplyForm(request.POST) if form.is_valid(): body = form.cleaned_data['body'] p = Post( thread=t, author=request.user, body=body, time=datetime.now(), ) p.save() return HttpResponseRedirect(p.get_absolute_url()) else: form = ReplyForm() return render_to_response('forum/reply.html', RequestContext(request, {'form': form, 'forum': t.forum, 'thread': t, }))
def addPost(request): if request.user.is_authenticated(): #Gets all the userinput data. And the hidden input fields that contains the ID's of the forum and thread the user is located in. postContent = request.GET['postContent'] forum_key = request.GET['forum_key'] thread_key = request.GET['thread_key'] #A cleaner that scans trough the thread description the users typed in and replaces the \n line breakers with html linebreakers (<br>) cleanPost = "" for a in postContent: if a in '\n': a += r'<br>' cleanPost += a #Creates a instance of a user so the Thred is bound to a creator. user = User.objects.get(username__exact=request.user.username) key_forum = Forum.objects.get(id=forum_key) key_thread = Thread.objects.get(id=thread_key, key_forum=forum_key) #creates a new insance of Post, inserts the values and finaly saves them. newPost = Post(content=cleanPost, displays=0, author= user, key_forum=key_forum, key_thread=key_thread ) newPost.save() bool = True return HttpResponseRedirect(reverse('forum.views.viewPosts', args=(forum_key,thread_key))) else: bool = False return HttpResponseRedirect(reverse('forum.views.viewForum'))
def reply(request, thread): """ If a thread isn't closed, and the user is logged in, post a reply to a thread. Note we don't have "nested" replies at this stage. """ if not request.user.is_authenticated(): return HttpResponseRedirect("%s?next=%s" % (LOGIN_URL, request.path)) t = get_object_or_404(Thread, pk=thread) if t.closed: return HttpResponseServerError() if not Forum.objects.has_access(t.forum, request.user.groups.all()): return HttpResponseForbidden() if request.method == "POST": form = ReplyForm(request.POST) if form.is_valid(): body = form.cleaned_data["body"] p = Post(thread=t, author=request.user, body=body, time=datetime.now()) p.save() # Send notifications (if installed) if notification: notification.send( User.objects.filter(forum_post_set__thread=t).distinct(), "forum_new_reply", {"post": p, "thread": t, "site": Site.objects.get_current()}, ) return HttpResponseRedirect(p.get_absolute_url()) else: form = ReplyForm() return render_to_response( "forum/reply.html", RequestContext(request, {"form": form, "forum": t.forum, "thread": t}) )
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 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_POST(request): commit = True try: post = Post(author=request.forum_user) post_form = PostForm(request.POST, instance=post) if post_form.is_valid(): post = post_form.save() topic = Topic(author=request.forum_user, first_post=post, last_post=post) topic_form = TopicForm(request.POST, instance=topic) if topic_form.is_valid(): topic = topic_form.save() post.topic = topic post.save() for category in topic.categories.all(): category.topic_count = category.topic_set.all().count() category.post_count = Post.objects\ .filter(topic__in=category.topic_set.all()).count() category.save() return redirect(post.get_absolute_url()) else: post_form = PostForm(request.POST) ctx = { 'forum_user': request.forum_user, 'topic_form': topic_form, 'post_form': post_form, } return render(request, 'forum/topic/create.html', ctx) finally: if commit: transaction.commit() else: transaction.rollback()
def newthread(request, forum): """ Rudimentary post function - this should probably use newforms, although not sure how that goes when we're updating two models. Only allows a user to post if they're logged in. """ if not request.user.is_authenticated(): return HttpResponseServerError() f = get_object_or_404(Forum, slug=forum) t = Thread( forum=f, title=request.POST.get('title'), ) t.save() p = Post( thread=t, author=request.user, body=request.POST.get('body'), time=datetime.now(), ) p.save() if request.POST.get('subscribe',False): s = Subscription( author=request.user, thread=t ) s.save() return HttpResponseRedirect(t.get_absolute_url())
def setUp(self): self.credentials = {'username': '******', 'password': '******'} self.user = User.objects.create_user(**self.credentials) self.user.save() self.post = Post(author=self.user, title='post', likes_total=100, text='this is a post', published_date=datetime.datetime(2019, 9, 4, tzinfo=pytz.UTC)) self.post.save() self.draft = Post(author=self.user, title='draft', likes_total=100, text='this is a draft') self.draft.save() self.shirt = Item(title='Shirt', price=300.0, category='Shirts', label='primary', slug='random-slug', description='shirt') self.shirt.image = SimpleUploadedFile( name='BE266_rose_top.jpg', content=open('/home/ubuntu/environment/ecommerce/media/random.jpg', 'rb').read(), content_type='image/jpeg') self.shirt.save()
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 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 test_account_me_renders_count_posts_with_authenticate(self): """ Test sprawdzajacy poprawnosc wyswietlania licznika postow uzytkownika """ # Rejestrujemy domyslnego uzytkownika self._login_user() # Pobieramy uzytkownika account = Account.objects.get(steamid64=self.steamid64) # Pobieramy token dla uzykownika token = self._get_token(account) # Ustawiamy headery self._create_credentials(token) # Tworzymy testową kategorie category = Category.objects.create(name="Testowa kategoria") # Tworzymy testowy temat, gdzie autorem jest stworzony uzytkownik thread = Thread.objects.create(title="Testowy watek", content="Testowa tresc", author=account, category=category) # Tworzymy dwa testowe posty w utworzonym temacie Post.objects.bulk_create([ Post(thread=thread, content="Testowa tresc", author=account), Post(thread=thread, content="Testowa tresc", author=account) ]) response = self.client.get('/api/accounts/me/') self.assertEqual(response.status_code, 200) self.assertEqual(response.data['threads'], 1) self.assertEqual(response.data['posts'], 2)
def newthread(request, forum): """ 新建帖子 """ f = get_object_or_404(Forum, slug=forum) if not Forum.objects.has_access(f, request.user.groups.all()): return Http404 if request.method == 'POST': form = CreateThreadForm(request.POST) if form.is_valid(): t = Thread( forum=f, title=form.cleaned_data['title'], ) t.save() p = Post( thread=t, author=request.user, body=form.cleaned_data['body'], time=datetime.now(), ) p.save() return HttpResponseRedirect(t.get_absolute_url()) else: form = CreateThreadForm() return render_to_response('forum/newthread.html', RequestContext(request, {'form': form, 'forum': f, }))
def create(request): language = get_language(request) user = get_user(request) if user is None: redirect('/login') error = None title = None body = None if request.method == 'POST': title = request.POST['title'] body = request.POST['body'] if not title: if language == 'pl': error = 'Musisz podac tytuł.' else: error = 'Title is required.' else: post = Post(title=title, body=body, author=user) post.save() return redirect('/') errors = [] if error is not None: errors.append(error) template = loader.get_template('posts/create.html') context = { 'user': user, 'errors': errors, 'title': title, 'body': body, 'language': language } return HttpResponse(template.render(context, request))
def post(self, section): try: post = Post(theme=g.data['theme'], description=g.data['description'], created_at=datetime.now(), section=section).save() except DatabaseError: abort(400) return make_response(jsonify(post.json()), 201)
def post_reply(request, slug, topic_id): quote = request.GET.get('quote', '') author = request.GET.get('author', '') if quote: quote = '<blockquote>' + quote + '<footer>' + author + '</footer></blockquote>' forum = get_object_or_404(Forum, slug=slug) posts = Post.objects.filter(topic=topic_id).order_by("created").reverse()[:3] topic = Topic.objects.get(pk=topic_id) form_title = '' if topic.last_post(): form_title = 'Re: ' + topic.last_post().title.replace('Re: ', '') default_data = {'title': form_title} form = PostForm(initial=default_data) if request.method == 'POST': quote = request.POST.get('quote', '') form = PostForm(request.POST) if form.is_valid(): post = Post() post.topic = topic post.title = form.cleaned_data['title'] post.body = quote + form.cleaned_data['body'] post.creator = request.user post.user_ip = request.META['REMOTE_ADDR'] post.save() return HttpResponseRedirect(reverse('topic-detail', args=(slug, topic.id, ))) return render(request, 'forum/reply.html', {'form': form, 'topic': topic, 'forum': forum, 'posts': posts, 'quote': quote})
def post_reply(request, topic_id): form = PostForm() topic = Topic.objects.get(pk=topic_id) if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = Post() post.topic = topic post.title = form.cleaned_data['title'] post.body = form.cleaned_data['body'] post.creator = request.user post.user_ip = request.META['REMOTE_ADDR'] post.save() return HttpResponseRedirect( reverse('topic-detail', args=(topic.id, ))) return render_to_response('django_simple_forum/reply.html', { 'form': form, 'topic': topic, }, context_instance=RequestContext(request))
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 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 newthread(request, forum): """ Rudimentary post function - this should probably use newforms, although not sure how that goes when we're updating two models. Only allows a user to post if they're logged in. """ if not request.user.is_authenticated(): return HttpResponseRedirect('%s?next=%s' % (LOGIN_URL, request.path)) f = get_object_or_404(Forum, slug=forum) if not Forum.objects.has_access(f, request.user.groups.all()): return HttpResponseForbidden() if request.method == 'POST': form = CreateThreadForm(request.POST) formset = AttachFileFormset(request.POST, request.FILES) if form.is_valid() and formset.is_valid(): t = Thread( forum=f, author=request.user, title=form.cleaned_data['title'], ) t.save() p = Post( thread=t, author=request.user, body=form.cleaned_data['body'], time=datetime.now(), ) p.save() formset.instance = p formset.save() if form.cleaned_data.get('subscribe', False): s = Subscription(author=request.user, thread=t) s.save() return HttpResponseRedirect(t.get_absolute_url()) else: form = CreateThreadForm() formset = AttachFileFormset() return render_to_response( 'forum/newthread.html', RequestContext(request, { 'form': form, 'formset': formset, 'forum': f, 'active': 7, }))
def post(self, *args, **kwargs): user = self.request.user form = PostForm(self.request.POST or None) if form.is_valid(): author = user title = form.cleaned_data.get('title') text = form.cleaned_data.get('text') post = Post(author=author, title=title, text=text) post.save() messages.success(self.request, "Your post has been added to your drafts but it has not been published yet") return redirect('post_draft_list', username=user.username)
def create_post(self, author, thread): new_post = Post( content = self.cleaned_data.get('content'), thread = thread, author = author, created = datetime.datetime.now(), ) new_post.save() thread.most_recent_post = new_post thread.save() return new_post
def save(self, request): post = Post() post.title = self.cleaned_data['title'] post.text = self.cleaned_data['text'] post.author = get_object_or_404(Profile, user=request.user) post.pub_date = timezone.now() tag = self.cleaned_data['tag'] post.save() list_of_tags(post, tag) post.save() return post
def form_valid(self, form): """ The user has provided valid credentials (this was checked in AuthenticationForm.is_valid()). So now we can log him in. """ #self.author = self.request.user.username content = form.cleaned_data['content'] title = form.cleaned_data['title'] new_post = Post(title=title, author=self.request.user, content=content) new_post.save() return HttpResponseRedirect('/post')
def new_post(): form = PostForm() if form.validate_on_submit(): if form.image.data: image = save_picture(form.image.data, 'post') post = Post(title=form.title.data, body=form.body.data, image=image, author=current_user) else: post = Post(title=form.title.data, body=form.body.data, author=current_user) db.session.add(post) db.session.commit() flash('Post successfully posted!', 'success') return redirect(url_for('home')) return render_template('create_post.html', title='New Post', form=form)
def post_reply(request, topic_id): form = PostForm() topic = Topic.objects.get(pk=topic_id) user = request.user if topic.closed: return render(request, 'personal/basic.html', {'content':['This topic is closed.']}) if topic.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 = PostForm(request.POST) if form.is_valid(): post = Post() post.topic = topic post.title = 'RE: '+topic.title post.body = bleach_clean(form.cleaned_data['body']) post.creator = request.user post.user_ip = get_client_ip(request) post.save() return HttpResponseRedirect(reverse('topic-detail', args=(topic.id, topic.slug, ))) return render_to_response('forum/reply.html', { 'form': form, 'topic': topic, 'forum': topic.forum, 'editing': False, }, context_instance=RequestContext(request))
def open_thread(request, threadSlug, page=0): try: theThread = Thread.objects.get(slug=threadSlug) except Thread.DoesNotExist: raise Http404("Thread doesn't exist.") if request.method == 'POST' and not theThread.is_locked: form = PostForm(request.POST) if form.is_valid(): text = form.cleaned_data['text'] newPost = Post(sub_forum=theThread.sub_forum, thread=theThread, user=request.user, text=text) newPost.save() return HttpResponseRedirect(newPost.get_url()) else: form = PostForm() postPerPage = settings.POSTS_PER_PAGE page = int(page) startPost = page * postPerPage allPosts = theThread.post_set.all() totalPosts = allPosts.count() totalPages = int(math.ceil(float(totalPosts) / float(postPerPage))) if page != 0 and startPost >= totalPosts: raise Http404("Invalid thread page.") pagePosts = allPosts[startPost:startPost + postPerPage] context = { 'thread': theThread, 'posts': pagePosts, 'threadSlug': threadSlug, 'page': page, 'pages': range(0, totalPages), 'form': form, 'paths': [theThread.sub_forum, theThread] } utilities.get_message(request, context) return render(request, 'thread.html', context)
def PostCreate(request): author = User.objects.get(pk=request.user.id) if request.method == 'POST': column_id = request.POST.get("column", "") column = get_object_or_404(Column, pk=int(column_id)) title = request.POST.get("title", "") content = request.POST.get("content", "") form = PostForm(request.POST) errors = [] if form.is_valid(): post = Post() post.title = title post.content = content post.author = author post.column = column post.save() #request.POST.get_absolute_url() return HttpResponseRedirect(reverse_lazy('forum:index')) else: #如果表单不正确,保存错误到errors列表中 for k, v in form.errors.items(): #v.as_text() 详见django.forms.util.ErrorList 中 errors.append(v.as_text()) if errors: return render(request, 'user_fail.html', {"errors": errors}) else: form = PostForm() #next = request.GET.get('next',None) #if next is None: #next = reverse_lazy('index') columns_list = Column.objects.all() return render(request, 'AddPost.html', { "form": form, "columns_list": columns_list })
def create(request, category_id): """Creation of a new thread from a category id. Shows a preview of the thread, if the user pressed the 'Preview' button instead of 'Reply'. """ category = get_object_or_404(Category, pk=category_id) preview_plain = False preview_html = False title_plain = False if request.method == 'POST': # Form has been submitted title_plain = request.POST['title'] title_html = prettify_title(title_plain) text_plain = request.POST['content'] if "submit" in request.POST: # "submit" button pressed if len(title_plain) > MAX_THREAD_TITLE_LENGTH: messages.error(request, long_title_error % MAX_THREAD_TITLE_LENGTH) preview_plain = text_plain preview_html = sanitized_smartdown(text_plain) else: user = request.user now = datetime.now() # UTC? text_html = sanitized_smartdown(text_plain) try: t = Thread(title_plain=title_plain, title_html=title_html, author=user, category=category, creation_date=now, latest_reply_date=now) t.save() p = Post(thread=t, creation_date=now, author=user, content_plain=text_plain, content_html=text_html) p.save() t.subscriber.add(request.user) except OperationalError: # Database interaction error messages.error(request, "%s") % operational_error else: # After successful submission return HttpResponseRedirect(reverse('forum.views.thread', args=(user.thread_set.all().order_by('-creation_date')[0].id,))) elif "preview" in request.POST: # "preview" button pressed preview_plain = text_plain preview_html = sanitized_smartdown(text_plain) return render(request, 'create.html', {'full_url' : request.build_absolute_uri(), 'current_site' : Site.objects.get_current(), 'category' : category, 'title' : title_plain, 'preview_plain': preview_plain, 'preview_html' : preview_html})
def newthread(request, forum): """ Rudimentary post function - this should probably use newforms, although not sure how that goes when we're updating two models. Only allows a user to post if they're logged in. """ if not request.user.is_authenticated(): return HttpResponseServerError() f = get_object_or_404(Forum, slug=forum) if not Forum.objects.has_access(f, request.user.groups.all()): return HttpResponseForbidden() if request.method == 'POST': form = CreateThreadForm(request.POST) if form.is_valid(): t = Thread( forum=f, title=form.cleaned_data['title'], ) t.save() p = Post( thread=t, author=request.user, body=form.cleaned_data['body'], time=datetime.now(), ) p.save() if form.cleaned_data.get('subscribe', False): s = Subscription( author=request.user, thread=t ) s.save() return HttpResponseRedirect(t.get_absolute_url()) else: form = CreateThreadForm() return render_to_response('forum/newthread.html', RequestContext(request, { 'form': form, 'forum': f, }))
def create_post(slug, id): if not g.user.is_authenticated(): flash(gettext('You need to log in to post in the forums.')) return redirect(url_for('index')) try: board = Board.query.filter(Board.slug == slug).one() except sql_exc: return redirect(url_for('.index')) try: thread = Thread.query.filter(Thread.id == id).one() except sql_exc: return redirect(url_for('.board', slug=slug)) form = forms.CreatePostForm() if form.validate_on_submit(): p = Post(content=form.content.data, author=current_user) thread.posts.append(p) db.session.flush() thread.updated = p.created db.session.commit() return redirect(url_for('.thread', slug=slug, id=id)) return render_template('forum/create_post.html', board=board, thread=thread, form=form)
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 forum_create(request): if request.method == 'POST': form = PostForm(request.POST) print(form.errors) if form.is_valid(): cd = form.cleaned_data post = Post(title=cd['title'], content=cd['body'], sender=request.user, summary=cd['outline'], category=cd['category']) post.save() return HttpResponseRedirect('/forum_index') else: form = PostForm() return render(request, 'forum_create.html', {'form': form})
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 form_valid(self, form): #此处有待加强安全验证 validate = self.request.POST.get('validate',None) formdata = form.cleaned_data if self.request.session.get('validate',None) != validate: return HttpResponse("验证码错误!<a href='/'>返回</a>") user = LoginUser.objects.get(username=self.request.user.username) #form.instance.author = user #form.instance.last_response = user formdata['author'] = user formdata['last_response'] = user p = Post(**formdata) p.save() user.levels += 5 #发帖一次积分加 5 user.save() return HttpResponse("发贴成功!<a href='/'>返回</a>")
def create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): content = form.cleaned_data['content'] title = form.cleaned_data['title'] post = Post(content=content, title=title, author=request.user) post.save() messages.success(request, f'New post created') return redirect('forum') else: form = PostForm() context = { 'PostForm': PostForm, } return render(request, 'forum/post_creation.html', context)
def form_valid(self, form): #此处有待加强安全验证 validate = self.request.POST.get('validate', None) formdata = form.cleaned_data if self.request.session.get('validate', None) != validate: return HttpResponse("验证码错误!<a href='/'>返回</a>") user = LoginUser.objects.get(username=self.request.user.username) #form.instance.author = user #form.instance.last_response = user formdata['author'] = user formdata['last_response'] = user p = Post(**formdata) p.save() user.levels += 5 #发帖一次积分加 5 user.save() return HttpResponse("发贴成功!<a href='/'>返回</a>")
def leech_category(session, category, category_data): response = session.get(FORUM_THREADS_URL, params=FORUM_THREADS_PARAMS(category_data['path'])) json_string = '\n'.join(response.text.split('\n')[1:]) threads_data = json.loads(json_string) for thread_data in threads_data: # Threads try: author = DogeUser.objects.get(login=thread_data['user']['login']) except: continue thread = Thread( title=thread_data['name'], category=category, author=author, created=thread_data['date'], ) thread.save() response = session.get(FORUM_POST_URL, params=FORUM_POST_PARAMS(thread_data['path'])) json_string = '\n'.join(response.text.split('\n')[1:]) posts_data = json.loads(json_string) for post_data in posts_data: # Posts try: author = DogeUser.objects.get(login=post_data['user']['login']) except: continue post = Post( thread=thread, author=author, content=post_data['content'], created=post_data['date'] ) post.save() for comment_data in post_data['comments']: # Comments try: author = DogeUser.objects.get(login=comment_data['user']['login']) except: continue comment = Comment( post=post, author=author, content=comment_data['content'], created=comment_data['date'] ) comment.save()
def dashboard(request): user = request.user post_and_answers = Post.get_last_posts_by_author_with_answers(user, posts_limit=5, answers_limit=3) last_threads_posted_in = Thread.get_last_threads_posted_in_with_posts(threads_limit=5, posts_limit=2) return render(request, 'dashboard.html', {'user': user, 'posts': post_and_answers, 'threads_last': last_threads_posted_in})
def newthread(request, forum): """Post a new thread. Rudimentary post function - this should probably use newforms, although not sure how that goes when we're updating two models. Only allows a user to post if they're logged in. @param forum: forum slug to create new thread for. @type forum: string @return: a view to post a new thread @rtype: Django response """ if not request.user.is_authenticated(): return HttpResponseRedirect("%s?next=%s" % (reverse("user_signin"), request.path)) f = get_object_or_404(Forum, slug=forum) if not Forum.objects.has_access(f, request.user.groups.all()): return HttpResponseForbidden() preview = False if request.method == "POST": form = CreateThreadForm(request.POST) if form.is_valid(): if request.POST.has_key("preview"): preview = {"title": form.cleaned_data["title"], "body": form.cleaned_data["body"]} else: t = Thread(forum=f, title=form.cleaned_data["title"]) t.save() p = Post(thread=t, author=request.user, body=form.cleaned_data["body"], time=datetime.now()) p.save() if form.cleaned_data.get("subscribe", False): s = Subscription(author=request.user, thread=t) s.save() return HttpResponseRedirect(t.get_absolute_url()) else: form = CreateThreadForm() return render_to_response( "forum/thread_new.html", RequestContext(request, {"form": form, "forum": f, "preview": preview, "section": forum}), )
def createpost(request): post = Post() if request.method == 'POST': serializer = ForumSerializer(post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def items(self, obj): self.title = "%s: %s" % (_("Last topics for blog"), obj.name) self.description = obj.desc self.link = obj.get_absolute_url() post_list = Post.get_rated_users_blog_posts(obj) posts = post_list[: settings.PAGE_LIMITATIONS["BLOG_POSTS"]] return posts
def reply(request, thread_id): """Grabs the contents of the <textarea> in the reply, gets the author id, slaps on the time stamp, and creates the post. Shows a preview of the post, if the user pressed the 'Preview' button instead of 'Reply'. """ thread = get_object_or_404(Thread, pk=thread_id) preview_plain = False preview_html = False if thread.is_locked: messages.info(request, "The thread %s has been locked and can not be posted in." % thread.title_html) return HttpResponseRedirect(reverse('forum.views.thread', args=(thread.id,))) elif thread.is_removed: messages.info(request, "The thread %s has been removed and is no longer available." % thread.title_html) return HttpResponseRedirect(reverse('forum.views.category', args=(thread.category.id,))) if request.method == 'POST': # Form been submitted text = request.POST['content'] if "submit" in request.POST: # "submit" button pressed user = request.user now = datetime.now() # UTC? html = sanitized_smartdown(text) try: p = Post(thread=thread, author=user, creation_date=now, content_plain=text, content_html=html) p.save() thread.latest_reply_date = now thread.save() except OperationalError: # Database interaction error messages.error(request, "%s") % operational_error else: # After successful submission return HttpResponseRedirect(reverse('forum.views.thread', args=(thread.id,))) elif "preview" in request.POST: # "preview" button pressed preview_plain = text preview_html = sanitized_smartdown(text) return render(request, 'reply.html', {'current_site' : Site.objects.get_current(), 'thread' : thread, 'preview_plain': preview_plain, 'preview_html' : preview_html})
def add_post(request, post_id=None): if post_id: post = get_object_or_404(Post, pk=post_id) if post.author != request.user: return HttpResponseForbidden("Only owner of this post is allowed to edit") else: post = Post(author=request.user) if request.method == 'POST': # If the form has been submitted... form = PostForm(request.POST, instance=post) # A form bound to the POST data if form.is_valid(): # All validation rules pass text = form.cleaned_data['content'] html = markdown(text) post.title = form.cleaned_data['title'] post.content = html post.tagnames = form.cleaned_data['tagnames'] post.save() return HttpResponseRedirect('/') else: # An unbound form form = PostForm(instance=post) return render(request, 'new_post.html', { 'form': form, 'post_id': post_id, })
def create_thread(self, author, category): new_thread = Thread( title = self.cleaned_data.get('title'), category = category, author = author, created = datetime.datetime.now(), ) new_thread.save() new_post = Post( content = self.cleaned_data.get('content'), thread = new_thread, author = author, created = datetime.datetime.now(), ) new_post.save() new_thread.most_recent_post = new_post new_thread.save() return new_thread
def write_post(request): if not request.user.is_authenticated: return redirect('home') if request.method == "POST": title = request.POST.get("title") content = request.POST.get("content") author = request.user new_post = Post(author=author, title=title, content=content, created=datetime.datetime.now()) new_post.save() return redirect('forum:post_successful') else: context = {"current_page": "write_post"} context['user'] = request.user context["form"] = PostForm() return render(request, "write_post.html", context)
def add_post(request, pk): threads = get_object_or_404(thread, pk=pk) if request.method == 'POST': post = Post(thread=threads) form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.creator = request.user post.save() # profile = User.objects.get(username=post.creator) # profile.posts = profile.posts + 1 # profile.save() return redirect('forum:thread', pk=pk) else: print(form.errors) else: form = PostForm() context_dict = {'form': form, 'thread': threads} return render(request, 'forum/add_post.html', context_dict)
def reply(request, thread): """ If a thread isn't closed, and the user is logged in, post a reply to a thread. Note we don't have "nested" replies at this stage. """ if not request.user.is_authenticated: raise HttpResponseServerError t = get_object_or_404(Thread, pk=thread) if t.closed: raise HttpResponseServerError body = request.POST.get('body', False) p = Post( thread=t, author=request.user, body=body, time=datetime.now(), ) p.save() return HttpResponseRedirect(p.get_absolute_url())
def add_post(request): p1 = Post (post_topic_id = request.POST['topic'], post_by_id=request.user.id , post_date=timezone.now(), post_content=request.POST['post_content']) p1.save() t = p1.post_topic if not request.user in t.topic_subscribers.all(): t.topic_subscribers.add(request.user) # Topic subscriptions t.subscribes += 1 t.save() content = "New post on : "+ t.topic_name +" by -"+ str(request.user) +"\n"+ p1.post_content url = "http://test.archilane.com/forum/topic/" + str(t.id) topic_subscribers = t.topic_subscribers.all() Notification.save_notification(content,url,'forum','Post','private',topic_subscribers) if t.topic_cat.subscribes > 0: cat_subscribers = t.topic_cat.cat_subscribers.all() Notification.save_notification(content,url,'forum','Category','private',cat_subscribers) #print(p1.post_topic.pk) #topic(request, p1.post_topic.pk) return HttpResponse(p1.post_topic.pk)
def mkpost(content="Test post.", creation_date=datetime.datetime.now()): """Helper function for making posts.""" p = Post() # _plain == _html, since the conversion happens in views.py, # which the object creation is not run through p.content_plain, p.content_html = content, content p.creation_date = creation_date p.author = mkuser() p.thread = mkthread() p.save() return p
def create_post(request): if not request.user.is_authenticated: return redirect("people:login") if request.method == "POST": post = json.loads(request.body) title = post['title'] body = post['body'] topic = Topic.objects.get(pk=int(post['topic'])) user = Person.objects.get(user=request.user) try: new_post = Post(title=title, body=body, owner=user, topic=topic) new_post.save() except Exception: return HttpResponse("Failed server error.") return HttpResponse("") topics = [{"id": x.pk, "name": x.name} for x in Topic.objects.all()] return render(request, "forum/create_post.html", context={"topics": topics})
def reply(request, thread, extra_context=None): """ If a thread isn't closed, and the user is logged in, post a reply to a thread. Note we don't have "nested" replies at this stage. """ t = get_object_or_404(Thread, pk=thread) if t.closed: return HttpResponseServerError() if not Forum.objects.has_access(t.forum, request.user.groups.all()): return HttpResponseForbidden() preview = False p = None if request.method == "POST": form = ReplyForm(request.POST) preview = request.POST.get('preview') p = Post( thread=t, author=request.user, time=datetime.now(), ) if form.is_valid(): p.body = form.cleaned_data['body'] if not preview: p.save() if not preview: return HttpResponseRedirect(p.get_absolute_url()) else: form = ReplyForm() return render_to_response('forum/reply.html', RequestContext(request, { 'form': form, 'forum': t.forum, 'post': p, 'preview': preview, 'thread': t, }))
def import_posts(self): print "* Importing posts" rows = self._query("select * from smf_messages") html_parser = HTMLParser.HTMLParser() for row in rows: if row['ID_MEMBER'] != 0: member = Member.objects.get(id=row['ID_MEMBER']) else: member = None post = Post( id=row['ID_MSG'], topic=Topic.objects.get(id=row['ID_TOPIC']), created_at=self.TZ.localize(datetime.datetime.fromtimestamp(row['posterTime'])), created_by=member, subject=html_parser.unescape(row['subject'].replace("Re:", "")), body=html_parser.unescape(row['body']).replace("<br />", "\n"), icon=row['icon']) disable_auto_now(post) post.save()
def add_post(request, forum, section, topic, preview): if not request.user.has_perm('forum.add_post'): raise Http404() topic = get_number_from_param_or_404(topic) 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 t = get_object_or_404(s.topic_set.all(), id=topic) if request.method == 'POST': errors = {'body': False} body = request.POST['input_body'] if len(body) > 1000: errors['body'] = True if not True in errors.values(): if not preview: try: p = create_and_get_post(creator=request.user, topic=t, body=body) except ValueError: # soon(30.08.12, 12:42) # FIXME # Обработать нормально эту ситуацию raise Http404() return redirect(p.get_absolute_url()) else: p = Post(creator=request.user, topic=t, body=body) return direct_to_template(request, 'forum/add_post.hdt', { 'post': p, 'topic': t, 'forum': f, 'section': s }) return direct_to_template(request, 'forum/add_post.hdt', { 'post_body': text_block, 'errors': errors }) else: raise Http404() #-------------------------------------------------------------------------------
def reply(request, pk): "View that handles POST request for a reply or renders the form for a reply" error = "" if request.method == "POST": p = request.POST if p["body_markdown"]: thread = Thread.objects.get(pk=pk) post = Post() form = PostForm(p, instance=post) post = form.save(commit=False) post.thread, post.creator = thread, request.user post.save() return HttpResponseRedirect(reverse("forum.views.thread", args=[pk]) + "?page=last") else: error = "Please enter a Reply\n" thread = Thread.objects.get(pk=pk) post_form = PostForm() return render_to_response( "forum/reply.html", add_csrf(request, thread=thread, post_form=post_form, error=error, pk=pk) )
def post(self, request, *args, **kwargs): if not request.user.is_authenticated(): return HttpResponseForbidden() self.object = None form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): self.object = form.save(commit=False) self.object.forum = self.forum self.object.title = form.cleaned_data['title'] self.object.save() post = Post(thread = self.object, author = request.user, body = form.cleaned_data['body'], time=timezone.now() ) post.save() self.object.latest_post_time=post.time #self.object.posts +=1 #wrong, 1 more self.object.save() if form.cleaned_data.get('subscribe', False): s = Subscription( author=request.user, thread=self.object, ) s.save() return self.form_valid(form) else: return self.form_invalid(form) self.object = None return super(ThreadCreateView, self).post(request, *args, **kwargs)
def post_create(request, topic_id, slug=None): topic = get_object_or_404(Topic, id=topic_id, is_closed=False) is_xhr = bool(request.REQUEST.get('xhr')) post = Post(topic=topic, author=request.forum_user) if request.method == 'POST': form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save() # update counters topic.post_count = topic.post_set.all().count() topic.updated = post.created topic.save() for category in topic.categories.all(): category.topic_count = category.topic_set.all().count() category.post_count = Post.objects\ .filter(topic__in=category.topic_set.all()).count() category.save() if is_xhr: return { 'status': 'ok', 'saved': True, 'url': post.get_absolute_url() } return _redirect_next(request, post) if is_xhr: return { 'status': 'ok', 'saved': False, 'errors': form.errors(), } else: form = PostForm() ctx = {'post_form': form, 'topic': topic} return render(request, 'forum/post/create.html', ctx)