def createThread(request): if not request.user.is_authenticated() or not request.user.is_active: return redirect('/auth/') if not request.method == 'POST': data = {'user': request.user, 'skills': Skill.objects.all()} return render(request, 'forum/createNew.html', data) requestReceived = json.loads(request.POST.get("thread")) json.dumps(requestReceived) threadTitle = requestReceived['threadTitle'] threadQuestion = requestReceived['threadQuestion'] skills = requestReceived['tags'] tagList = [] currentTimeStamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M') for skillId in skills: skill = Skill.objects.get(id=skillId) tagList.append(skill) print skill.skillName thread = Thread(title=threadTitle, author=request.user, publishedDate=currentTimeStamp, tags=tagList, questionText=threadQuestion) thread.save() return HttpResponse()
def new_thread(request, forumSlug): try: forum = SubForum.objects.get(slug=forumSlug) except SubForum.DoesNotExist: raise Http404("Sub-forum doesn't exist.") if request.method == 'POST': form = ThreadForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] theThread = Thread(sub_forum=forum, user=request.user, title=title, slug='', text=content) utilities.unique_slugify(theThread, title) theThread.save() return HttpResponseRedirect(theThread.get_url()) else: form = ThreadForm() context = {'forumSlug': forumSlug, 'form': form} return render(request, 'new/new_thread.html', context)
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 create_thread(request): data = json.loads(request.body) title = data.get('title') description = data.get('description') location = data.get('location') precision = data.get('precision') joining = data.get('joining') joining_value = data.get('joiningValue') publishing = data.get('publishing') publishing_value = data.get('publishingValue') thread_id = data.get('threadId') thread_name = data.get('threadName') moderator = data.get('moderator') is_open = data.get('is_open') space = data.get('space') did = data.get('did') thread = Thread(title=title, description=description, location=location, precision=precision, joining_policy=joining, joining_value=joining_value, publishing_policy=publishing, publishing_value=publishing_value, thread_id=thread_id, thread_name=thread_name, moderator=moderator, is_open=is_open, space=space, did=did) thread.save() sub = Subscription(thread=thread, address=moderator) sub.save() return JsonResponse(to_dict(thread), status=201)
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 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 addThread(request): #Checks if user is authed. Function that i used before i discoverd the decorator. if request.user.is_authenticated(): #Gets all the userinput data, And the dynamicly generated ID. id = request.GET['id'] name = request.GET['threadName'] description = request.GET['threadDescription'] forum = Forum.objects.get(id=id) #Creates a instance of a user so the Thred is bound to a creator. user = User.objects.get(username__exact=request.user.username) #A cleaner that scans trough the thread description the users typed in and replaces the \n line breakers with html linebreakers (<br>) cleanDescription = "" for a in description: if a in '\n': a += r'<br>' cleanDescription += a #creates a new insance of Thread, inserts the values and finaly saves them. newTread = Thread(key_forum=forum, title=name, content=cleanDescription, displays=0, author= user ) newTread.save() bool = True #Sends the user back to the viewThreads function and dispalys the forum the user added the newthread in. return HttpResponseRedirect(reverse('forum.views.viewThreads', args=(id,))) else: #If faulthy access user gets sentback to startpage bool = False return HttpResponseRedirect(reverse('forum.views.viewForum'))
def newThread(request): if request.method == 'POST': # If the form has been submitted... form = ThreadForm(request.POST) # A form bound to the POST data if 'login' in request.session: usr = User.objects.get(login= request.session['login']) else: return HttpResponseRedirect('/error/2/') if form.is_valid(): # All validation rules pass thread = Thread( title= form.cleaned_data['title'], content = form.cleaned_data['content'], category = form.cleaned_data['category'], user = usr, response = [], rating = [] ) thread.save() return HttpResponseRedirect('/thread/' + str(thread.id)) # Redirect after POST else: form = ThreadForm() # An unbound form categories = Category.objects.all() return render(request, 'newThread.html', { 'form': form, 'categories' : categories, })
def post_create_thread(request): errors = [] params = deepValidateAndFetch(request, errors) if len(errors) == 0: with transaction.atomic(): thread = Thread(title=params['title'], author=params['author'], section_id=params['section']) if params['visibility'] == 'private': thread.recipient = params['recipient'] if params['visibility'] == 'class': thread.lesson = params['lesson'] if params['visibility'] == 'public': thread.professor = params['professor'] thread.save() if params['skills_fetched']: thread.skills = params['fetched_skills'] thread.save() sendNotification(getWSNotificationForNewThread(thread)) original_message = Message( content=params['content'], thread=thread, author=params['author'], created_date=utc.localize(datetime.now()), modified_date=utc.localize(datetime.now())) original_message.save() sendNotification(getNotificationForNewMessage(original_message)) return redirect(thread) else: skills, sections = get_skills(request) params['skills'] = skills params['sections'] = sections if params['skills_fetched']: params['selected_skills'] = map(lambda x: x.id, params['fetched_skills']) else: params['selected_skills'] = [] if params['section'] is not None: params['selected_section'] = int(params['section']) return render(request, "forum/new_thread.haml", { "errors": errors, "data": params })
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(request): #if not request.user.is_authenticated(): # return redirect('/login/') if request.method == 'GET': return render(request, 'post.html') elif request.method == 'POST': subforum = Subforum.objects.get(name = request.POST['course']) title = request.POST['title'] content = request.POST['text'] thread = Thread(poster = request.user, content = content, title = title, subforum = subforum) thread.save() return redirect(thread.get_url())
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 post(request): #if not request.user.is_authenticated(): # return redirect('/login/') if request.method == 'GET': return render(request, 'post.html') elif request.method == 'POST': subforum = Subforum.objects.get(name=request.POST['course']) title = request.POST['title'] content = request.POST['text'] thread = Thread(poster=request.user, content=content, title=title, subforum=subforum) thread.save() return redirect(thread.get_url())
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): 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() Post = comments.get_model() ct = ContentType.objects.get_for_model(Thread) p = Post( content_type=ct, object_pk=t.pk, user=request.user, comment=form.cleaned_data['body'], submit_date=datetime.now(), site=Site.objects.get_current(), ) p.save() t.latest_post = p t.comment = p t.save() """ undecided 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 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 import_threads(f): cat_map = {1: 1, 2: 2, 3: 3, 4: 4, 5: 6, 6: 7, 7: 5} # mapping categories threads = json.loads(fix_json(f)) # loading threads existing_threads = {} for thread in Thread.objects.iterator(): existing_threads[thread.pk] = thread.category_id # prepare tokens for threads tokens = set() print("Creating tokens...", end='\r') while len(tokens) != len(threads): tokens.add(keygen()) # Prepare bulk bulk = [] for i, thread in enumerate(threads): print("Preparing threads... {}/{}".format(i + 1, len(threads)), end='\r') if thread['idtopic'] in existing_threads: continue isSticky = True if thread['postit'] == 1 else False bulk.append( Thread( pk=int(thread['idtopic']), category=Category.objects.get(pk=cat_map[thread['idforum']]), title=HTMLParser().unescape(str(thread['sujet']))[:80], author=ForumUser.objects.get(pk=thread['idmembre']), icon=str(thread['icone']) + '.gif', viewCount=int(thread['nbvues']), isSticky=isSticky, cessionToken=tokens.pop())) print("Creating threads in the database...", end='\r') if bulk: Thread.objects.bulk_create(bulk)
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 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 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 mkthread(title="Test Thread", creation_date=datetime.datetime.now(), latest_reply_date=datetime.datetime.now()): """Helper function for making threads.""" t = Thread() t.title_plain, t.title_html = title, title t.creation_date = creation_date t.latest_reply_date = latest_reply_date t.category = mkcategory() t.author = mkuser() t.save() return t
def new_thread(request): if 'uid' in request.session: uid = request.session['uid'] title = request.POST.get('title', '') content = request.POST.get('content', '') tag = request.POST.get('tag', '') reply = request.POST.get('reply', 0) new_model = Thread(uid=uid, time=datetime.now(), title=title, content=content, tag=tag, reply=reply) try: new_model.save() return JsonResponse({'ok': True, 'id': new_model.id}) except: return JsonResponse({'ok': False, 'msg': '发帖失败:服务器异常'}) else: return JsonResponse({'ok': False, 'msg': '请登录后重试'})
def create(self, validated_data): subforum = validated_data['subforum'] user = validated_data['user'] title = validated_data['title'] post = validated_data['post'] thread_obj = Thread( subforum=subforum, user=user, title=title, ) thread_obj.save() post_obj = Post( user=thread_obj.user, thread=thread_obj, content=post, ) post_obj.save() thread_slug = Thread.objects.get(id=thread_obj.id).thread_slug validated_data['thread_slug'] = thread_slug return validated_data
def new_thread(request, pk): "View that handles POST request for a new thread or renders the form for a new thread" error = "" if request.method == "POST": p = request.POST if p["body_markdown"] and p["title"]: forum = Forum.objects.get(pk=pk) thread = Thread() form = ThreadForm(p, instance=thread) thread = form.save(commit=False) thread.forum, thread.creator = forum, request.user thread.save() return HttpResponseRedirect(reverse("forum.views.thread", args=[thread.pk])) else: error = "Please enter the Title and Body\n" forum = Forum.objects.get(pk=pk) thread_form = ThreadForm() return render_to_response( "forum/new_thread.html", add_csrf(request, forum=forum, thread_form=thread_form, error=error, pk=pk) )
def test_get_latest_with_threads(self): board = Board.create('board name', 'bcode') user = User.objects.create(username='******', email='*****@*****.**') pub_date = timezone.now() thread_list = [] for i in range(10): thread_list.append(Thread.create(title='thread' + str(i), message=str(i), author=user, board=board)) thread_list[i].first_post.pub_date = pub_date - datetime.timedelta(minutes=i) thread_list[i].first_post.save() threads1 = board.get_latest() threads2 = board.get_latest(5) threads3 = board.get_latest('pippo') self.assertEqual(threads1, thread_list) self.assertEqual(threads2, thread_list[:5]) self.assertEqual(threads3, thread_list)
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 reply_to_unanswered_help_request(self, user): """ The student who responds is the tutor """ self.tutor = user """ Status shifts to accepted """ self.state = HelpRequest.ACCEPTED """ We create the thread between the two students """ thread = Thread(title="Aide " + self.student.user.first_name + " par " + user.user.first_name, author=self.student.user, recipient=user.user) thread.save() thread.skills = Skill.objects.filter(pk__in=self.skill.all()) thread.save() self.thread = thread self.save()
def forum(request): last_five = Thread.objects.all().order_by('-id')[:5] if request.method == 'POST': form = ThreadForm(request.POST) if form.is_valid(): creator = form.cleaned_data['name'] text = form.cleaned_data['subject'] Thread(text=text, creator=creator).save() messages.success(request, 'Thanks for getting involved, dude') return redirect(reverse('forum:forum')) else: form = ThreadForm() cform = CommentForm() return render(request, 'forum/forum.html', { 'last_five': last_five, 'form': form, 'cform': cform })
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 create_thread(slug): 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')) form = forms.CreateThreadForm() if form.validate_on_submit(): t = Thread(name=form.name.data, board=board, author=current_user) db.session.add(t) db.session.flush() p = Post(content=form.content.data, author=current_user) t.posts.append(p) db.session.commit() return redirect(url_for('.board', slug=slug)) return render_template('forum/create_thread.html', board=board, form=form)
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(data=request.POST, files=request.FILES) #return HttpResponseRedirect('/POST'+str(request.FILES['file'])) #return HttpResponseRedirect('/POST'+str(form.is_valid())) if form.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() if form.cleaned_data.get('subscribe', False): s = Subscription( author=request.user, thread=t ) s.save() for attachedfilefield in form.files: #file_path = '%s%s' % (settings.MEDIA_ROOT, form.files[attachedfilefield]) attachment_file = form.files[attachedfilefield] attach=Attachment() attach.handle_uploaded_attachment(p, attachment_file, attached_by = request.user, title = attachment_file.name, summary = t.title ) return HttpResponseRedirect(t.get_absolute_url()) else: form = CreateThreadForm() return render_to_response('forum/newthread.html', RequestContext(request, { 'form': form, 'forum': f, }))
from wsgi import * with open('/home/dotcloud/environment.json') as f: env = json.load(f) from django.contrib.auth.models import User from forum.models import Category, Thread, Post c, created = Category.objects.get_or_create(pk=1) if created: c.title_plain = "The Forum" c.title_html = "The Forum" c.save() now = datetime.datetime.now() # UTC? user = User.objects.get(pk=1) t = Thread(category=c, author=user, title_plain="Your First Thread", title_html="Your First Thread", creation_date=now, latest_reply_date=now) t.save() p = Post(thread=t, author=user, content_plain="Play around with the formatting and buttons.", content_html="<p>Play around with the formatting and buttons.</p>", creation_date=now) p.save()
def previewthread(request, forum): """ Renders a preview of the new post and gives the user the option to modify it before posting. 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, site=settings.SITE_ID) if not Forum.objects.has_access(f, request.user): return HttpResponseForbidden() if request.method == "POST": if not can_post(f, request.user): return HttpResponseForbidden cache = get_forum_cache() key = make_cache_forum_key(request.user, forum, settings.SITE_ID) if cache and forum in FORUM_FLOOD_CONTROL: if cache.get(key): post_title, post_url, expiry = cache.get(key) expiry = timeuntil(datetime.fromtimestamp(expiry)) messages.error(request, "You can't post a thread in the forum %s for %s." % (f.title, expiry)) return HttpResponseRedirect(post_url) form = CreateThreadForm(request.POST) if form.is_valid(): t = Thread( forum=f, title=form.cleaned_data['title'], ) Post = comments.get_model() ct = ContentType.objects.get_for_model(Thread) # If previewing, render preview and form. if "preview" in request.POST: return render_to_response('forum/previewthread.html', RequestContext(request, { 'form': form, 'forum': f, 'thread': t, 'comment': form.cleaned_data['body'], 'user': request.user, })) # No preview means we're ready to save the post. else: t.save() p = Post( content_type=ct, object_pk=t.pk, user=request.user, comment=form.cleaned_data['body'], submit_date=datetime.now(), site=Site.objects.get_current(), ) p.save() t.latest_post = p t.comment = p t.save() Thread.nonrel_objects.push_to_list('%s-latest-comments' % t.forum.slug, t, trim=30) thread_created.send(sender=Thread, instance=t, author=request.user) if cache and forum in FORUM_FLOOD_CONTROL: cache.set(key, (t.title, t.get_absolute_url(), get_forum_expire_datetime(forum)), FORUM_FLOOD_CONTROL.get(forum, FORUM_POST_EXPIRE_IN)) return HttpResponseRedirect(t.get_absolute_url()) else: form = CreateThreadForm() return render_to_response('forum/newthread.html', RequestContext(request, { 'form': form, 'forum': f, }))
def handle(self, *args, **options): self.before_handle() f_name = "__js-1-50.json" f = open('fake/fake_threads/' + f_name, encoding='utf-8') s = json.load(f) s.reverse() # for i in s: # if not i['tittle']: # print(i) if not len(s): return j = 1 for i in s: self.get_data_ready(i) t = Thread() t.main_class = self.main_class_instance t.sub_class = self.sub_class_instance t.tittle = i['tittle'] if not '?' in t.tittle: t.tittle = t.tittle + "?" print(str(j), t.tittle) j = j + 1 t.create_user = self.user if i['content']: t.content = i['content'][0] else: t.content = "" t.like = self.like t.dislike = self.dislike t.reply = self.reply t.view = self.view t.save() self.add_comment(t.id, i['comment'])
def save(self, user): thread = Thread(title=self.cleaned_data['title'], last_comment_date=datetime.now()) thread.save() comment = Comment(author=user, thread=thread, content=self.cleaned_data['content']) comment.save()
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 merge_thread(request, thread_id): """Merge the posts of two threads into one single thread. The posts are ordered chronologically in the new thread, the old threads are locked, and a notification post is created in all three threads. """ thread = get_object_or_404(Thread, pk=thread_id) new_title_plain = thread.title_plain new_title_html = thread.title_html other_thread = False if request.method == 'POST' and "cancel" not in request.POST: other_thread = get_object_or_404(Thread, pk=request.POST['other-thread-id']) # try --- fix new_title_plain = request.POST['new-thread-title'] new_title_html = prettify_title(new_title_plain) if request.method == 'POST' and "merge" in request.POST: if len(new_title_plain) > MAX_THREAD_TITLE_LENGTH: messages.error(request, long_title_error % MAX_THREAD_TITLE_LENGTH) elif request.method == 'POST' and "confirm" in request.POST: now = datetime.now() # UTC? user = request.user t = Thread(title_plain=new_title_plain, title_html=new_title_html, creation_date=now, author=user, category=thread.category, latest_reply_date=now) t.save() # Update posts in two threads to point to new thread t thread.post_set.all().update(thread=t.id) other_thread.post_set.all().update(thread=t.id) # Make post notification in ALL threads # Do not append a redundant full stop if new_title_plain[-1] not in set([".!?"]) \ and new_title_plain[-3:-1] not in set(['."', '!"', '?"', ".'", "!'", "?'"]): end = "." else: end = "" message = "(*%s* was merged with *%s* by *%s* into *[%s](%s)*%s)" % \ (thread.title_html, other_thread.title_html, user.username, new_title_html, t.get_absolute_url(), end) html = sanitized_smartdown(message) p1 = Post(creation_date=now, author=user, thread=t, content_plain=message, content_html=html) p2 = Post(creation_date=now, author=user, thread=thread, content_plain=message, content_html=html) p3 = Post(creation_date=now, author=user, thread=other_thread, content_plain=message, content_html=html) p1.save() p2.save() p3.save() # Lock original threads thread.is_locked = True other_thread.is_locked = True thread.save() other_thread.save() return HttpResponseRedirect(reverse('forum.views.thread', args=(t.id,))) return render(request, 'merge.html', {'full_url' : request.build_absolute_uri(), 'current_site': Site.objects.get_current(), 'thread' : thread, 'other_thread': other_thread, 'new_title' : new_title_plain})
def test_thread_view_with_no_responses(self): board = Board.create('boardname', 'bc') author = User.objects.create_user(username='******', password='******', email='*****@*****.**') thread = Thread.create('thread title', 'thread message', board, author) response = self.client.get(reverse('forum:thread', kwargs={'thread_pk': thread.pk, 'page': ''}), follow=True) self.assertEqual(response.status_code, 200)
def handle(self, *args, **options): self.before_handle() f_name = self.filename f = open('fake/fake_threads/' + f_name, encoding='utf-8') s = json.load(f) s.reverse() # for i in s: # if not i['tittle']: # print(i) if not len(s): return j = 1 for i in s: # if j < 19: # j = j+1 # continue try: self.get_data_ready(i) t = Thread() t.main_class = self.main_class_instance t.sub_class = self.sub_class_instance t.tittle = i['tittle'] if not '?' in t.tittle: t.tittle = t.tittle + "?" print(str(j), t.tittle) j = j + 1 t.create_user = self.user if i['content']: t.content = str(i['content'][0]) else: t.content = "" t.like = self.like t.dislike = self.dislike t.reply = self.reply t.view = self.view t.save() import jieba.posseg as pseg from forum.models import TAG accept_type = [ 'n', 'ns', 'eng', 'nr', 'l', 'vn', 'nz', 's', 'j', 'nt', 'nrt' ] s = t.tittle words = pseg.cut(s) for word, flag in words: if flag in accept_type: tag = TAG() tag.thread = t tag.name = word[:30] tag.save() self.add_comment(t.id, i['comment']) except: pass
def previewthread(request, forum): """ Renders a preview of the new post and gives the user the option to modify it before posting. If called without a POST, redirects to newthread. 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): return HttpResponseForbidden() if request.method == "POST": form = CreateThreadForm(request.POST) if form.is_valid(): t = Thread( forum=f, title=form.cleaned_data['title'], ) Post = comments.get_model() ct = ContentType.objects.get_for_model(Thread) # If previewing, render preview and form. if "preview" in request.POST: return render_to_response('forum/previewthread.html', RequestContext(request, { 'form': form, 'forum': f, 'thread': t, 'comment': form.cleaned_data['body'], 'user': request.user, })) # No preview means we're ready to save the post. else: t.save() p = Post( content_type=ct, object_pk=t.pk, user=request.user, comment=form.cleaned_data['body'], submit_date=datetime.now(), site=Site.objects.get_current(), ) p.save() t.latest_post = p t.comment = p t.save() thread_created.send(sender=Thread, instance=t, author=request.user) return HttpResponseRedirect(t.get_absolute_url()) else: form = CreateThreadForm() return render_to_response('forum/newthread.html', RequestContext(request, { 'form': form, 'forum': f, }))