Пример #1
0
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,
                                                       }))
Пример #2
0
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}))
Пример #3
0
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,
        }))
Пример #4
0
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,
        }))
Пример #5
0
def editthread(request, forum, thread):
    """
    Edit the thread title and body.
    """
    thread = get_object_or_404(Thread, slug=thread, forum__slug=forum,
                               forum__site=settings.SITE_ID)

    if not request.user.is_authenticated or thread.comment.user != request.user:
        return HttpResponseForbidden()

    if request.method == "POST":

        form = CreateThreadForm(request.POST, is_edit=True)
        if form.is_valid():

            # If previewing, render preview and form.
            if "preview" in request.POST:
                return render_to_response('forum/previewthread.html',
                    RequestContext(request, {
                        'form': form,
                        'forum': thread.forum,
                        'thread': thread,
                        'comment': form.cleaned_data['body'],
                        'user': request.user,
                    }))

            # No preview means we're ready to save the post.
            else:
                thread.title = form.cleaned_data['title']
                thread.comment.comment = form.cleaned_data['body']
                thread.sticky = form.cleaned_data['sticky']
                thread.save()
                thread.comment.save()

                return HttpResponseRedirect(thread.get_absolute_url())

    else:
        form = CreateThreadForm(initial={
            "title": thread.title,
            "body": thread.comment.comment,
            "sticky": thread.sticky
            })

    return render_to_response('forum/previewthread.html',
        RequestContext(request, {
            'form': form,
            'forum': thread.forum,
            'thread': thread,
            'comment': thread.comment.comment,
            'user': request.user,
        }))
Пример #6
0
def thread_create_view(request, subcategory_name):
    try:
        subcategory = Subcategory.objects.get(title=subcategory_name)
    except Subcategory.DoesNotExist:
        return unknown_subcategory(request)

    if subcategory.category.staff_only and not request.user.has_perm(
            "create_thread_in_staff_only"):
        return insufficient_permission(request)

    form = CreateThreadForm()

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

        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            prefix = form.cleaned_data['prefix']

            if Thread.objects.filter(title=title).exists():
                form.add_error('title',
                               "Thread with this name already exists.")
                return render(request, 'forum/thread-create.html', {
                    'form': form,
                    'subcategory': subcategory
                })

            if prefix is not None:
                if not ThreadPrefix.objects.filter(name=prefix).exists():
                    form.add_error('prefix', "Unknown thread prefix.")
                    return render(request, 'forum/thread-create.html', {
                        'form': form,
                        'subcategory': subcategory
                    })

            thread = Thread.objects.create(title=title,
                                           author=request.user,
                                           subcategory=subcategory,
                                           prefix=prefix)
            thread.save()

            message = Message.objects.create(thread=thread,
                                             content=content,
                                             author=request.user)
            message.save()

            message.author.userprofile.check_add_achievements(
                Achievement.THREAD_COUNT)

            return redirect(thread_view, thread_title=thread.title)

    return render(request, 'forum/thread-create.html', {
        'form': form,
        'subcategory': subcategory
    })
Пример #7
0
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,
        }))
Пример #8
0
def forum(request, slug):
    """View the list of threads within a forum.

    Threads are sorted by their sticky flag, followed by their 
    most recent post.

    @param slug: forum's slug
    @type slug: string
    @return: list of threads of forum identified by slug
    @rtype: Django object_list
    @raise Http404: if slug doesn't yield an existing forum.
    """
    try:
        f = Forum.objects.for_groups(
            request.user.groups.all()).select_related().get(slug=slug)
    except Forum.DoesNotExist:
        raise Http404

    form = CreateThreadForm()
    child_forums = f.child.for_groups(request.user.groups.all())
    return object_list(request,
                       queryset=f.thread_set.select_related().all(),
                       paginate_by=FORUM_PAGINATION,
                       template_object_name='thread',
                       template_name='forum/thread_list.html',
                       extra_context={
                           'forum': f,
                           'child_forums': child_forums,
                           'form': form,
                           'login': {
                               'reason': _('create a new thread'),
                               'next': f.get_absolute_url(),
                           },
                           'section': 'forum',
                       })
Пример #9
0
def search(request, q):
    """
    Displays a list of threads within a forum.
    Threads are sorted by their sticky flag, followed by their
    most recent post.
    """

    try:
        f = Forum.objects.for_groups(request.user.groups.all()).select_related().get(slug=slug)
    except Forum.DoesNotExist:
        #raise Http404(_("Not Found"))
        return HttpResponseForbidden(_('Sorry, you need permission to continue.'))

    form = CreateThreadForm()
    child_forums = f.child.for_groups(request.user.groups.all())
    return object_list( request,
                        queryset=f.thread_set.select_related().all(),
                        paginate_by=FORUM_PAGINATION,
                        template_object_name='thread',
                        template_name='forum/thread_list.html',
                        extra_context = {
                            'forum': f,
                            'child_forums': child_forums,
                            'form': form,
                        })
Пример #10
0
def forum(request, slug):
    """
	Displays a list of threads within a forum.
	Threads are sorted by their sticky flag, followed by their 
	most recent post.
	"""
    try:
        f = Forum.objects.for_groups(
            request.user.groups.all()).select_related().get(slug=slug)
    except Forum.DoesNotExist:
        raise Http404

    form = CreateThreadForm()
    formset = AttachFileFormset()

    child_forums = f.child.for_groups(request.user.groups.all())

    return object_list(request,
                       queryset=f.thread_set.select_related().all(),
                       paginate_by=FORUM_PAGINATION,
                       template_object_name='thread',
                       template_name='forum/thread_list.html',
                       extra_context={
                           'forum': f,
                           'formset': formset,
                           'child_forums': child_forums,
                           'form': form,
                           'active': 7,
                       })
Пример #11
0
def forum(request, slug):
    """
    显示当前论坛下面的帖子数
    select_related()增加了缓存性能
    """
    the_groups = request.user.groups.all()

    # 防止直接输入不存在或者没有权限的地址进行访问
    try:
        f = Forum.objects.for_groups(the_groups).select_related().get(
            slug=slug)
    except Forum.DoesNotExist:
        raise Http404

    form = CreateThreadForm()
    child_forums = f.child.for_groups(the_groups)
    return object_list(request,
                       queryset=f.thread_set.select_related().all(),
                       paginate_by=FORUM_PER_PAGE,
                       template_object_name='thread',
                       template_name='forum/thread_list.html',
                       extra_context={
                           'forum': f,
                           'child_forums': child_forums,
                           'form': form,
                       })
Пример #12
0
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}),
    )
Пример #13
0
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,
        }))
Пример #14
0
    def get_context_data(self, **kwargs):
        context = super(ForumView, self).get_context_data(**kwargs)

        form = CreateThreadForm()

        extra_context = {
            'forum': self.forum,
            'child_forums': self.child_forums,
            'active_threads': self.active_threads,
            'recent_threads': self.recent_threads,
            'form': form
        }
        context.update(extra_context)

        return context
Пример #15
0
def forum(request, slug, flag_partner=False):
	"""
	Displays a list of threads within a forum.
	Threads are sorted by their sticky flag, followed by their 
	most recent post.
	"""
	try:
		if flag_partner:
			if request.user.is_authenticated() and request.user.get_profile().is_partner():
				f = Forum.objects.for_groups(request.user.groups.all()).select_related().get(slug=slug, for_partner=flag_partner)
			else:
				messages.add_message(request, messages.ERROR, 'Пожалуйста, авторизируйтесь как партнер.')
				return redirect('/accounts/login/?next=%s' % request.path)
		else: 
			f = Forum.objects.for_groups(request.user.groups.all()).select_related().get(slug=slug, for_partner=flag_partner)
	except Forum.DoesNotExist:
		raise Http404

	form = CreateThreadForm()
	formset = AttachFileFormset()
	
	child_forums = f.child.for_groups(request.user.groups.all())
	
	return object_list(
		request,
		queryset=f.thread_set.select_related().all(),
		paginate_by=FORUM_PAGINATION,
		template_object_name='thread',
		template_name='forum/thread_list.html',
		extra_context = {
			'forum': f,
			'formset': formset,
			'child_forums': child_forums,
			'form': form,
			'flag_partner':flag_partner
		}
	)
Пример #16
0
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, 
        }))
Пример #17
0
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,
        }))
Пример #18
0
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,
        }))
Пример #19
0
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,
        }))