Пример #1
0
def newtopic(request):
    user = request.user
    form = None
    if request.method == 'POST':
        form = TopicForm(request.POST)
        if form.is_valid() and form.save():
            return redirect('/topics/')
        elif form.is_valid():
            form.non_field_errors = "Failed to save"
        else:
            form.non_field_errors = 'form is not valid'
    else:
        form = TopicForm()
    return render(request, 'forum/form.html', {"form": form})
Пример #2
0
def newtopic(request):
    user = request.user
    form = None
    if request.method == 'POST':
        form = TopicForm(request.POST)
        if form.is_valid() and form.save():
            return redirect('/topics/')
        elif form.is_valid():
            form.non_field_errors = "Failed to save"
        else:
            form.non_field_errors = 'form is not valid'
    else:
        form = TopicForm()
    return render(request, 'forum/form.html', {"form": form})
Пример #3
0
def add(request):
    if request.method == 'POST':
        form = TopicForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/")
    else:
        form = TopicForm()
        return render_to_response('form.html',{'form': form}, context_instance=RequestContext(request))
Пример #4
0
def new_topic(request):
    """Определяет новую тему."""
    if request.method != 'POST':
        # Данные не отправлялись; создается пустая форма.
        form = TopicForm()
    else:
        # Отправлены данные POST; обработать данные.
        form = TopicForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))
    context = {'form': form}
    return render(request, 'learning_logs/new_topic.html', context)
Пример #5
0
def add_topic(request):
    '''Add a new topic'''
    tform = None
    if request.method == 'POST':
        tform = TopicForm(request.POST)
        if tform.is_valid():
            t = tform.save()
            'If topic was added successfully, send them to that topic page'
            return goto_topic(t, 'Now you can start adding options')
    
    if not tform:
        tform = TopicForm()

    return render_to_response('dovote/add_topic.html',
                              dict(tform=tform),
                              context_instance=RequestContext(request))
Пример #6
0
def add_topic(request, event_id):
    e = Event.objects.get(id=event_id)

    if request.method == 'POST':
        f = TopicForm(request.POST)
        if f.is_valid():
            t = f.save(commit=false)#not push yet.
            #more values... to event yes.
            t.event = e
            t.save()
            return HttpResponseRedirect('/event/get/%s' % event_id)
    else:
        f=TopicForm()
    args ={}
    args.update(csrf(request))

    args['article']=a
    args['form']=f

    return render_to_response('add_topic.html',args)
Пример #7
0
def create_topic(request):
    """ Create a topic. """

    if request.method == "POST":
        form = TopicForm(request.POST)
        if form.is_valid():
            t = form.save(commit=False)

            if not request.user.is_authenticated():
                # Record what they posted and then send them to login
                request.session['topic'] = form.cleaned_data
                request.session['topic_include_image'] = request.POST.get("include_image")
                request.session['topic_image'] = request.POST.get("image")
                request.session['login_prefix'] = render_to_string(
                    "login_new_topic.html",
                    form.cleaned_data,
                    context_instance=RequestContext(request))
                return redirect(reverse("account_login") + "?next=/create_topic")

            t.created_by = request.user

            if request.POST.get("include_image"):
                t.description = "![](" + request.POST['image'] + ")\n\n" + t.description
                t.thumbnail_url = request.POST['image']
            t.save()
            messages.success(request, "Your topic has been created")
            return redirect("discussion", t.pk)
    elif 'topic' in request.session and request.user.is_authenticated():
        t = Topic(title=request.session['topic']['title'], description=request.session['topic']['description'], url=request.session['topic']['url'])
        t.created_by = request.user
        if request.session.get("topic_include_image"):
            t.description = "![](" + request.session['topic_image'] + ")\n\n" + t.description
            t.thumbnail_url = request.session['topic_image']
        t.save()
        messages.success(request, "Your topic has been created")
        del request.session['topic']
        return redirect("discussion", t.pk)
    messages.error(request, "There was a problem submitting this link.")
    return redirect("index")
Пример #8
0
def new(request):
    if request.method == 'POST':
        topic_form = TopicForm(request.POST)
        post_form = PostForm(request.POST)

        if topic_form.is_valid() and post_form.is_valid():
            topic = topic_form.save()
            post = post_form.save(commit=False)
            post.topic = topic
            post.author = request.user
            post.save()
            return redirect('/forum/%d' % topic.id)
    else:
        topic_form = TopicForm()
        post_form = PostForm()

    return render_to_response('forum/new.html',
                              {
                                  'topic_form': topic_form,
                                  'post_form': post_form
                              },
                              context_instance=RequestContext(request))
Пример #9
0
def create_topic(request, forum):
    forum = Forum.objects.select_related('Moderator').get(slug=forum)
    if request.method == "POST":
        topic_form      = TopicForm(request.POST, instance=Topic())
        message_form    = MessageForm(request.POST, instance=Message())
        if topic_form.is_valid():
            if message_form.is_valid():
                topic = topic_form.save(commit=False)
                topic.category    = forum.category
                topic.forum       = forum
                topic.user        = request.user
                topic.last_user   = request.user
                topic.save()
                message = message_form.save(commit=False)
                message.category    = forum.category
                message.forum       = forum
                message.topic       = topic
                message.user        = request.user
                message.save()
                topic.message = message
                topic.last_message = message
                topic.save()
                action.send(request.user, verb='created a topic', target=topic)
                return HttpResponseRedirect(reverse('djero.views.topic', kwargs={
                    'category'  : forum.category.slug,
                    'forum'     : forum.slug,
                    'topic'     : topic.slug,
                }))
        else:
            return HttpResponse(topic_form.errors)
    else:
        topic_form      = TopicForm()
        message_form    = MessageForm()
        return render(request, "forum/create_topic.html", {
            "forum"         : forum,
            "topic_form"    : topic_form,
            "message_form"  : message_form,
        })
Пример #10
0
def new(request):
    """Creates a new topic in a forum."""

    try:
        forum_pk = request.GET["forum"]
    except KeyError:
        raise Http404
    forum = get_object_or_404(Forum, pk=forum_pk)
    if not forum.can_read(request.user):
        raise PermissionDenied
    if request.method == "POST":

        # If the client is using the "preview" button

        if "preview" in request.POST:
            form = TopicForm(initial={"title": request.POST["title"],
                                      "subtitle": request.POST["subtitle"],
                                      "text": request.POST["text"]})
            return render_template("forum/topic/new.html",
                                   {"forum": forum,
                                    "form": form,
                                    "text": request.POST["text"]})
        form = TopicForm(request.POST)
        data = form.data
        if form.is_valid():

            # Treat title

            (tags, title) = get_tag_by_title(data["title"])

            # Creating the thread
            n_topic = Topic()
            n_topic.forum = forum
            n_topic.title = title
            n_topic.subtitle = data["subtitle"]
            n_topic.pubdate = datetime.now()
            n_topic.author = request.user
            n_topic.save()
            # add tags

            n_topic.add_tags(tags)
            n_topic.save()
            # Adding the first message

            post = Post()
            post.topic = n_topic
            post.author = request.user
            post.text = data["text"]
            post.text_html = emarkdown(request.POST["text"])
            post.pubdate = datetime.now()
            post.position = 1
            post.ip_address = get_client_ip(request)
            post.save()
            n_topic.last_message = post
            n_topic.save()

            # Follow the topic

            follow(n_topic)
            return redirect(n_topic.get_absolute_url())
    else:
        form = TopicForm()

    return render_template("forum/topic/new.html", {"forum": forum, "form": form})
Пример #11
0
def new(request):
    """Creates a new topic in a forum."""

    try:
        forum_pk = request.GET["forum"]
    except:
        # problem in variable format
        raise Http404
    forum = get_object_or_404(Forum, pk=forum_pk)
    if not forum.can_read(request.user):
        raise PermissionDenied
    if request.method == "POST":

        # If the client is using the "preview" button

        if "preview" in request.POST:
            form = TopicForm(initial={"title": request.POST["title"],
                                      "subtitle": request.POST["subtitle"],
                                      "text": request.POST["text"]})
            return render_template("forum/topic/new.html",
                                   {"forum": forum,
                                    "form": form,
                                    "text": request.POST["text"]})
        form = TopicForm(request.POST)
        data = form.data
        if form.is_valid():

            # Treat title

            (tags, title) = get_tag_by_title(data["title"])

            # Creating the thread
            n_topic = Topic()
            n_topic.forum = forum
            n_topic.title = title
            n_topic.subtitle = data["subtitle"]
            n_topic.pubdate = datetime.now()
            n_topic.author = request.user
            n_topic.save()
            # add tags

            n_topic.add_tags(tags)
            n_topic.save()
            # Adding the first message

            post = Post()
            post.topic = n_topic
            post.author = request.user
            post.text = data["text"]
            post.text_html = emarkdown(request.POST["text"])
            post.pubdate = datetime.now()
            post.position = 1
            post.ip_address = get_client_ip(request)
            post.save()
            n_topic.last_message = post
            n_topic.save()

            # Follow the topic

            follow(n_topic)
            return redirect(n_topic.get_absolute_url())
    else:
        form = TopicForm()

    return render_template("forum/topic/new.html", {"forum": forum, "form": form})
Пример #12
0
def edit_post(request):
    """Edit the given user's post."""

    try:
        post_pk = request.GET["message"]
    except:
        # problem in variable format
        raise Http404
    post = get_object_or_404(Post, pk=post_pk)
    if not post.topic.forum.can_read(request.user):
        raise PermissionDenied
    g_topic = None
    if post.position <= 1:
        g_topic = get_object_or_404(Topic, pk=post.topic.pk)

    # Making sure the user is allowed to do that. Author of the post must to be
    # the user logged.

    if post.author != request.user \
            and not request.user.has_perm("forum.change_post") and "signal_message" \
            not in request.POST:
        raise PermissionDenied
    if post.author != request.user and request.method == "GET" \
            and request.user.has_perm("forum.change_post"):
        messages.warning(
            request, u'Vous éditez ce message en tant que '
            u'modérateur (auteur : {}). Soyez encore plus '
            u'prudent lors de l\'édition de celui-ci !'.format(
                post.author.username))
    if request.method == "POST":
        if "delete_message" in request.POST:
            if post.author == request.user \
                    or request.user.has_perm("forum.change_post"):
                post.alerts.all().delete()
                post.is_visible = False
                if request.user.has_perm("forum.change_post"):
                    post.text_hidden = request.POST["text_hidden"]
                post.editor = request.user
                messages.success(request, u"Le message est désormais masqué.")
        if "show_message" in request.POST:
            if request.user.has_perm("forum.change_post"):
                post.is_visible = True
                post.text_hidden = ""
        if "signal_message" in request.POST:
            alert = Alert()
            alert.author = request.user
            alert.comment = post
            alert.scope = Alert.FORUM
            alert.text = request.POST['signal_text']
            alert.pubdate = datetime.now()
            alert.save()
            messages.success(
                request, u'Une alerte a été envoyée '
                u'à l\'équipe concernant '
                u'ce message.')

        # Using the preview button

        if "preview" in request.POST:
            if g_topic:
                form = TopicForm(
                    initial={
                        "title": request.POST["title"],
                        "subtitle": request.POST["subtitle"],
                        "text": request.POST["text"]
                    })
            else:
                form = PostForm(post.topic,
                                request.user,
                                initial={"text": request.POST["text"]})
            form.helper.form_action = reverse("zds.forum.views.edit_post") \
                + "?message=" + str(post_pk)
            return render_template(
                "forum/post/edit.html", {
                    "post": post,
                    "topic": post.topic,
                    "text": request.POST["text"],
                    "form": form,
                })

        if "delete_message" not in request.POST and "signal_message" \
                not in request.POST and "show_message" not in request.POST:
            # The user just sent data, handle them

            if request.POST["text"].strip() != "":
                # check if the form is valid
                form = TopicForm(request.POST)
                if not form.is_valid() and g_topic:
                    return render_template(
                        "forum/post/edit.html", {
                            "post": post,
                            "topic": post.topic,
                            "text": post.text,
                            "form": form,
                        })
                post.text = request.POST["text"]
                post.text_html = emarkdown(request.POST["text"])
                post.update = datetime.now()
                post.editor = request.user

            # Modifying the thread info

            if g_topic:
                (tags, title) = get_tag_by_title(request.POST["title"])
                g_topic.title = title
                g_topic.subtitle = request.POST["subtitle"]
                g_topic.save()
                g_topic.tags.clear()

                # add tags

                g_topic.add_tags(tags)
        post.save()
        return redirect(post.get_absolute_url())
    else:
        if g_topic:
            prefix = u""
            for tag in g_topic.tags.all():
                prefix += u"[{0}]".format(tag.title)
            form = TopicForm(
                initial={
                    "title": u"{0} {1}".format(prefix, g_topic.title).strip(),
                    "subtitle": g_topic.subtitle,
                    "text": post.text
                })
        else:
            form = PostForm(post.topic,
                            request.user,
                            initial={"text": post.text})
        form.helper.form_action = reverse("zds.forum.views.edit_post") \
            + "?message=" + str(post_pk)
        return render_template("forum/post/edit.html", {
            "post": post,
            "topic": post.topic,
            "text": post.text,
            "form": form,
        })
Пример #13
0
def forum_topics(request, slug):

    forum = get_object_or_404(Forum, slug=slug)

    if not request.user.has_perm("can_view_topics", forum):
        return HttpResponseForbidden()

    topics_qs = Topic.objects.filter(forum=forum)
    # пагинация сообщений в топике форума
    paginator = Paginator(topics_qs, 20)
    page_num = request.GET.get('page', '1')

    if page_num == 'last':
        page_num = paginator.num_pages
    try:
        page = paginator.page(int(page_num))
    except (InvalidPage, ValueError):
        raise Http404()

    #    topics = paginator.object_list
    if request.method == 'POST':

        if forum.closed:
            return HttpResponseForbidden()

        topic_form = TopicForm(request.POST, prefix='topic')
        article_form = ArticleForm(request.POST, prefix='article')

        if topic_form.is_valid() and article_form.is_valid():
            if not request.user.has_perm("can_create_topics", forum):
                return HttpResponseForbidden()

            topic = topic_form.save(commit=False)

            if request.user.has_perm('can_hide_topics', forum):
                topic.public = True
            else:
                topic.public = False

            topic.forum = forum
            topic.save()
            article = article_form.save(commit=False)

            article.public = True

            article.author = request.user
            article.topic = topic
            article.save()

            groups = get_groups_with_perms(forum, attach_perms=True)
            for group in groups:
                if u"can_create_topics" in groups[group]:
                    assign(u"can_add_articles", group, topic)
                #                    assign(u"can_view_articles", group, topic)
                if u"can_view_topics" in groups[group]:
                    assign(u"can_view_articles", group, topic)

            if request.user.has_perm('can_hide_topics', forum):
                return redirect('forum:frontend:articles',
                                slug=forum.slug,
                                id=topic.id)
            else:
                return redirect('forum:frontend:topics', slug=forum.slug)
    else:
        topic_form = TopicForm(prefix='topic')
        article_form = ArticleForm(prefix='article')
    return render(
        request,
        'forum/frontend/topics.html',
        {
            'forum': forum,
            #        'topics': topics,
            'topic_form': topic_form,
            'article_form': article_form,
            'page': page,
        })
Пример #14
0
def forum_topics(request, slug):


    forum = get_object_or_404(Forum, slug=slug)



    if not request.user.has_perm("can_view_topics", forum):
        return HttpResponseForbidden()

    topics_qs = Topic.objects.filter(forum=forum)
    # пагинация сообщений в топике форума
    paginator = Paginator(topics_qs, 20)
    page_num = request.GET.get('page', '1')

    if page_num == 'last':
        page_num = paginator.num_pages
    try:
        page = paginator.page(int(page_num))
    except (InvalidPage, ValueError):
        raise Http404()

    #    topics = paginator.object_list
    if request.method == 'POST':

        if forum.closed:
            return HttpResponseForbidden()

        topic_form = TopicForm(request.POST, prefix='topic')
        article_form = ArticleForm(request.POST, prefix='article')

        if topic_form.is_valid() and article_form.is_valid():
            if not request.user.has_perm("can_create_topics", forum):
                return HttpResponseForbidden()

            topic = topic_form.save(commit=False)

            if request.user.has_perm('can_hide_topics', forum):
                topic.public = True
            else:
                topic.public = False

            topic.forum = forum
            topic.save()
            article = article_form.save(commit=False)

            article.public = True

            article.author = request.user
            article.topic = topic
            article.save()

            groups =  get_groups_with_perms(forum, attach_perms=True)
            for group in groups:
                if  u"can_create_topics" in  groups[group]:
                    assign(u"can_add_articles", group, topic)
                #                    assign(u"can_view_articles", group, topic)
                if  u"can_view_topics" in  groups[group]:
                    assign(u"can_view_articles", group, topic)

            if request.user.has_perm('can_hide_topics', forum):
                return redirect('forum:frontend:articles', slug=forum.slug, id=topic.id)
            else:
                return redirect('forum:frontend:topics', slug=forum.slug)
    else:
        topic_form = TopicForm(prefix='topic')
        article_form = ArticleForm(prefix='article')
    return render(request, 'forum/frontend/topics.html', {
        'forum': forum,
        #        'topics': topics,
        'topic_form': topic_form,
        'article_form': article_form,
        'page': page,
        })
Пример #15
0
def new(request):
    '''
    Creates a new topic in a forum
    '''
    try:
        forum_pk = request.GET['forum']
    except KeyError:
        raise Http404

    forum = get_object_or_404(Forum, pk=forum_pk)

    if request.method == 'POST':
        # If the client is using the "preview" button
        if 'preview' in request.POST:
            return render_template(
                'forum/new.html', {
                    'forum': forum,
                    'title': request.POST['title'],
                    'subtitle': request.POST['subtitle'],
                    'text': request.POST['text'],
                })

        form = TopicForm(request.POST)
        if form.is_valid() and data['text'].strip() != '':
            data = form.data
            # Creating the thread
            n_topic = Topic()
            n_topic.forum = forum
            n_topic.title = data['title']
            n_topic.subtitle = data['subtitle']
            n_topic.pubdate = datetime.now()
            n_topic.author = request.user
            n_topic.save()

            # Adding the first message
            post = Post()
            post.topic = n_topic
            post.author = request.user
            post.text = data['text']
            post.text_html = emarkdown(request.POST['text'])
            post.pubdate = datetime.now()
            post.position = 1
            post.ip_address = get_client_ip(request)
            post.save()

            n_topic.last_message = post
            n_topic.save()

            # Follow the topic
            follow(n_topic)

            return redirect(n_topic.get_absolute_url())

        else:
            # TODO: add errors to the form and return it
            raise Http404

    else:

        form = TopicForm()
        return render_template('forum/new.html', {
            'form': form,
            'forum': forum
        })