Esempio n. 1
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))
Esempio n. 2
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)
Esempio n. 3
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})
Esempio n. 4
0
def article_edit(request, subject, aid):
    article = Articles.objects.select_related().get(pk=aid)

    perm_edit_article = False
    if request.user == article.name:
        perm_edit_article = True

    if subject == 'new':
        form = NewForm(instance=article)
    elif subject == 'topic':
        form = TopicForm(instance=article)

    if request.method == 'POST':
        article.title = request.POST['title']
        article.category = request.POST['category']
        article.label = request.POST['label']
        article.content = request.POST['content']
        if subject == 'new':
            article.source = request.POST['source']
            article.sourceurl = request.POST['sourceurl']
            article.team = request.POST['team']
        elif subject == 'topic':
            article.category2 = request.POST['category2']
        article.save()
        return HttpResponseRedirect('/articles/%s/' % aid)
    return render_to_response("article_edit.html",{'form': form, 'perm_edit_article': perm_edit_article},\
                        context_instance=RequestContext(request))
Esempio n. 5
0
def create():
    data = request.get_json()

    form = TopicForm(**data)
    if form.validate():
        form_data = form.data
        form_data['ip'] = request.remote_addr

        try:
            topic = g.user.create_topic(**form_data)
            alert = dict(
                type='success',
                messages=
                _("Your topic has been created successfully. You will be redirected to it shortly"
                  ))

            redirect = topic.get_url('view')
            cache.update_sorted_topics(topic, 'date_created')
            return jsonify({
                "data": topic.json_data(),
                "alert": alert,
                "redirect": redirect
            })
        except ModelException, me:
            db_session.rollback()
            return json_error(type=me.type, messages=me.message)
        except Exception, e:
            logging.error(e)
            db_session.rollback()
            return json_error_database()
Esempio n. 6
0
def create_topic():
    """Docstring."""
    if only_check():
        tform = TopicForm()
        tform.validate_on_submit()  # to get error messages to the browser
        if request.method == 'POST':
            if tform.validate() is False:
                flash('All fields are required.', 'critical')
                return check_and_render('topics_create.html',
                                        form=tform)
            else:
                if validate_topic(tform.topic_name.data) is False:
                    create_topic_entry(tform.topic_name.data,
                                       tform.partition_count.data,
                                       tform.replication_factor.data)
                    flash('Added Topic: ' +
                          tform.topic_name.data)
                    return redirect(url_for('topics'))
                else:
                    flash('This topic name exists already.', 'critical')
                    return check_and_render('topics_create.html',
                                            form=tform)
        elif request.method == 'GET':
            return check_and_render('topics_create.html',
                                    form=tform)
    else:
        return check_and_render('index.html')
Esempio n. 7
0
def topics(request):
    topic = TopicForm()
    topics = api_client.get(topic)
    return render(request, 'forum/topiclist.html', {
        'topics': topics['objects'],
        'meta': topics['meta']
    })
Esempio n. 8
0
def new_post():
    form = TopicForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('create_topic.html', form=form, legend='New Topic')
Esempio n. 9
0
def update_post(post_id):
    post = Post.query.get_or_404(post_id)

    form = TopicForm()
    if form.validate_on_submit():
        post.title = form.title.data
        db.session.commit()
        return redirect(url_for('post', post_id=post.id))
    elif request.method == 'GET':
        form.title.data = post.title

    return render_template('create_post.html', form=form)
Esempio n. 10
0
def chat(user):
    # Creating new topics.
    if request.method == 'POST':
        if user.topics_full():
            return render_template('/index.html',
                                   topics=get_topics(),
                                   full=True,
                                   user=user.user)
        form = TopicForm(request.form)
        if form.validate():
            form.add(user.user)
        return render_template('/index.html',
                               topics=get_topics(),
                               form=form,
                               user=user.user)

    # Deleting topics.
    if request.method == 'GET' and request.args.get('del_topic', False):
        user.del_topic(request.args['del_topic'])
    form = TopicForm()
    return render_template('/index.html',
                           topics=get_topics(),
                           form=form,
                           user=user.user)
Esempio n. 11
0
def bbs_add_topic():
    node_str = urllib.unquote(request.args.get('node', "").strip())
    node = None
    if node_str:
        node = Node.query.filter(Node.name == node_str).first()
        if not node:
            return render_template("node_not_found.html",
                                   next=url_for('.bbs_add_topic'),
                                   name=node_str)

    form = TopicForm(request.form)
    form.node.choices = Section.query.get_all_nodes()
    if node_str:
        form.node.data = node.title
    if request.method == 'POST' and form.validate():
        if not node:
            node = Node.query.filter(
                Node.title == form.data["node"].strip()).first()
            if not node:
                form.node.errors.append(u"节点不存在!")
                return render_template("add_topic.html", form=form)
        section = node.section
        topic = Topic(user=current_user,
                      title=form.data['title'].strip(),
                      content=form.data["content"],
                      tags=form.data["tags"],
                      created=datetime.now(),
                      last_modified=datetime.now(),
                      last_reply_at=datetime.now())
        topic.section = section
        topic.node = node

        #db.session.add(topic)
        node.topic_count += 1
        #db.session.add(node)
        section.topic_count += 1
        #db.session.add(section)
        current_user.profile.topics += 1
        db.session.add_all([topic, node, section, current_user.profile])
        db.session.commit()
        return redirect(url_for(".bbs_topic", id=topic.id))
    if node_str:
        action_url = url_for(".bbs_add_topic", node=node_str)
    else:
        action_url = url_for(".bbs_add_topic")
    return render_template("add_topic.html", form=form, action_url=action_url)
Esempio n. 12
0
def private_chat(username):
    form = TopicForm()
    topics = Topic.query.all()
    users = User.query.all()
    messages = PrivateMessage.query.all()

    chat_partner = User.query.filter_by(email=username).first()

    if chat_partner is None:
        return redirect(url_for('chat'))

    session['room'] = convertToNumber(chat_partner.email) + convertToNumber(
        session['email'])
    session['private'] = chat_partner.email

    if 'email' not in session:
        return redirect(url_for('signin'))

    user = User.query.filter_by(email=session['email']).first()

    if user is None:
        return redirect(url_for('signin'))
    else:
        if request.method == 'POST':
            if form.validate() == False:
                return render_template('private.html',
                                       form=form,
                                       topics=topics,
                                       users=users,
                                       messages=messages,
                                       private=username)
            else:
                uid = user.uid
                newtopic = Topic(form.topicname.data, uid)
                db.session.add(newtopic)
                db.session.commit()
                session['topic'] = newtopic.topicname
                return redirect('/chat/' + newtopic.topicname)

        if request.method == 'GET':
            return render_template('private.html',
                                   form=form,
                                   topics=topics,
                                   users=users,
                                   messages=messages,
                                   private=username)
Esempio n. 13
0
 def post(self):
     if not self.has_permission:
         return
     node_id = force_int(self.get_argument('node_id', 0), 0)
     node = Node.get(id=node_id)
     user = self.current_user
     form = TopicForm(self.request.arguments)
     if form.validate():
         topic = form.save(user=user)
         result = {'status': 'success', 'message': '主题创建成功',
                 'topic_url': topic.url}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(topic.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("topic/create.html", form=form, node=node)
Esempio n. 14
0
 def post(self, topic_id):
     if not self.has_permission:
         return
     topic = Topic.get(id=topic_id)
     if not topic or (topic.author != self.current_user and not self.current_user.is_admin):
         return self.redirect_next_url()
     user = self.current_user
     form = TopicForm(self.request.arguments)
     if form.validate():
         topic = form.save(user=user, topic=topic)
         result = {'status': 'success', 'message': '主题修改成功',
                 'topic_url': topic.url}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(topic.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("topic/create.html", form=form, node=topic.node)
Esempio n. 15
0
async def _topic(request, topic_id=None):
    form = TopicForm(request)
    form.status.data = int(form.status.data)

    topic = None
    if topic_id is not None:
        topic = await SpecialTopic.get_or_404(topic_id)

    if request.method in ('POST', 'PUT') and form.validate():
        dct = defaultdict(dict)
        for k in copy.copy(request.form):
            if k.startswith('posts'):
                match = FORM_REGEX.search(k)
                if match:
                    key = match['key']
                    val = request.form[k][0]
                    dct[match['index']][key] = int(val) if key == 'id' else val
                    del request.form[k]

        title = form.title.data
        if topic_id is None:
            topic = await SpecialTopic.filter(title=title).first()
        if not topic:
            topic = SpecialTopic()

        form.populate_obj(topic)
        if dct:
            indexes = [
                (i['id'], int(index))
                for index, i in sorted(dct.items(), key=lambda i: i[0])
            ]
        else:
            indexes = []
        if topic_id is not None:
            await topic.set_indexes(indexes)
        await topic.save()
        if topic_id is None:
            await topic.set_indexes(indexes)
        ok = True
    else:
        ok = False
    topic = await topic.to_sync_dict()
    return json({'topic': topic if topic else None, 'ok': ok})
Esempio n. 16
0
def topic(request, id=None):
    form = TopicForm(initial={'id': id})
    comment_form = CommentForm(initial={"topic": id})
    if (request.POST):
        comment_form = CommentForm(request.POST)
        comment_form.user = request.user.username
        if comment_form.is_valid():
            if comment_form.save(request=request):
                message = "Comment submitted"
                return redirect('/topic/{}'.format(id))
            else:
                message = "Failed to save comment"
        else:
            pass
    try:
        topic = api_client.get(form)
        comments = api_client.get(form, sub_url="topic/{}/comments".format(id))
    except (Exception) as err:
        message = "Failed to retrieve topic and/or comments"

    new_comments = {}

    class node():
        def __init__(self, value):
            self.value = value
            self.children = []

        def add_child(self, obj):
            self.children.append(obj)

    nodes = dict((e["id"], node(e)) for e in comments['objects'])
    for e in comments['objects']:
        if e["in_reply_to"]:
            if not nodes.get(e["in_reply_to"], False):
                nodes[e["in_reply_to"]] = node({"is_hidden": True})
            nodes[e["in_reply_to"]].add_child(nodes[e["id"]])

    return render(request, 'forum/topic.html', {
        'topic': topic,
        'comments': nodes,
        'form': comment_form
    })
Esempio n. 17
0
def Topic_fu():
    from models import Topic
    from forms import TopicForm
    if request.method == "POST":
        form = TopicForm(request.form)
        if form.validate():
            topicsql = Topic(**form.data)
            db.session.add(topicsql)
            db.session.commit()
        else:
            return render_template("errors.html",
                                   errors_text=str(form.errors)), 400
    try:
        quotes = Topic.query.all()
    except Exception as e:
        return render_template("errors.html", errors_text=str(e)), 500
    else:
        return render_template('_take_topic_template.html',
                               quotes=quotes,
                               link_to=url_for('Topic_fu') + "/")
Esempio n. 18
0
File: admin.py Progetto: ihyf/blog
async def _topic(request: Request, topic_id: Optional[Any] = None):
    form = TopicForm(request)
    form.status.data = int(form.status.data)

    topic = None
    if topic_id is not None:
        topic = await SpecialTopic.get_or_404(topic_id)

    if request.method in ('POST', 'PUT') and form.validate():
        dct: DefaultDict[str, Dict[str, int]] = defaultdict(dict)
        for k in copy.copy(request.form):
            if k.startswith('posts'):
                match = FORM_REGEX.search(k)
                if (match := FORM_REGEX.search(k)):
                    key = match['key']  # type: ignore
                    val = request.form[k][0]
                    dct[match['index']][key] = (  # type: ignore
                        int(val) if key == 'id' else val)
                    del request.form[k]

        title = form.title.data
        if topic_id is None:
            topic = await SpecialTopic.filter(title=title).first()
        if not topic:
            topic = SpecialTopic()

        form.populate_obj(topic)
        if dct:
            indexes = [
                (i['id'], int(index))
                for index, i in sorted(dct.items(), key=lambda i: i[0])
            ]
        else:
            indexes = []
        if topic_id is not None:
            await topic.set_indexes(indexes)
        await topic.save()
        if topic_id is None:
            await topic.set_indexes(indexes)
        ok = True
Esempio n. 19
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")
Esempio n. 20
0
def random():
    form = TopicForm()
    users = User.query.all()
    messages = RandomMessage.query.all()

    if 'email' not in session:
        return redirect(url_for('signin'))

    user = User.query.filter_by(email=session['email']).first()
    if user is None:
        return redirect(url_for('signin'))

    if user.random is "":
        return redirect(url_for('random_setting'))

    session['room'] = convertToNumber(
        user.random + "random") + convertToNumber(session['email'] + "random")
    session['random'] = user.random

    return render_template('random.html',
                           form=form,
                           user=user,
                           messages=messages)
Esempio n. 21
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
        })
Esempio n. 22
0
    def request_form_data():
        model = request.json['model']
        form_type = request.json['formType']
        if (model == 'category' and form_type == 'create'):
            form = CategoryForm()
            return render_template('category_form.html',
                                   sub_url='/api/categories',
                                   sub_method='post',
                                   model=model.capitalize(),
                                   object={},
                                   action=form_type.capitalize(),
                                   form=form)

        if (model == 'category' and form_type == 'update'):
            cat_id = request.json['id']
            category = Category.query.get_or_404(cat_id)
            url = '/api/categories/' + cat_id + '/update'
            form = CategoryForm()
            return render_template('category_form.html',
                                   sub_url=url,
                                   sub_method='patch',
                                   model=model.capitalize(),
                                   object=category,
                                   action=form_type.capitalize(),
                                   form=form)

        if (model == 'topic' and form_type == 'create'):
            parent_id = request.json['parentId']
            form = TopicForm()
            return render_template('topic_form.html',
                                   sub_url='/api/topics',
                                   sub_method='post',
                                   model=model.capitalize(),
                                   object={},
                                   parent_id=parent_id,
                                   action=form_type.capitalize(),
                                   form=form)

        if (model == 'topic' and form_type == 'update'):
            top_id = request.json['id']
            topic = Topic.query.get_or_404(top_id)
            url = '/api/topics/' + top_id + '/update'
            form = TopicForm()
            return render_template('topic_form.html',
                                   sub_url=url,
                                   sub_method='patch',
                                   model=model.capitalize(),
                                   object=topic,
                                   parent_id=topic.category_id,
                                   action=form_type.capitalize(),
                                   form=form)

        if (model == 'concept' and form_type == 'create'):
            parent_id = request.json['parentId']
            form = ConceptForm()
            return render_template('concept_form.html',
                                   sub_url='/api/concepts',
                                   sub_method='post',
                                   model=model.capitalize(),
                                   object={},
                                   parent_id=parent_id,
                                   action=form_type.capitalize(),
                                   form=form)

        if (model == 'concept' and form_type == 'update'):
            con_id = request.json['id']
            concept = Concept.query.get_or_404(con_id)
            concept.formatted_tags = concept.return_formatted_tags()
            url = '/api/concepts/' + con_id + '/update'
            form = ConceptForm()
            return render_template('concept_form.html',
                                   sub_url=url,
                                   sub_method='patch',
                                   model=model.capitalize(),
                                   object=concept,
                                   parent_id=concept.topic_id,
                                   action=form_type.capitalize(),
                                   form=form)
Esempio n. 23
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,
        })
Esempio n. 24
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 \xe9ditez ce message en tant que '
                         u'mod\xe9rateur (auteur : {}). Soyez encore plus '
                         u'prudent lors de l\'\xe9dition 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() != "":
                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,
        })
Esempio n. 25
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})
Esempio n. 26
0
def show_chatroom(chatroom_title):
    form = TopicForm()
    topics = Topic.query.all()
    users = User.query.all()
    messages = Message.query.all()
    banned_from = []
    moderated_rooms = []
    banned_users = []

    topic = Topic.query.filter_by(topicname=chatroom_title).first()

    user = User.query.filter_by(email=session['email']).first()

    if BannedUser.query.filter_by(user_id=user.uid).first() is not None:
        flagged_rooms = BannedUser.query.filter_by(user_id=user.uid).all()
        for room in flagged_rooms:
            if room.times_flagged >= 5 and room.topic_id != 1:
                print("banned from:")
                print(room.topic_id)
                banned_from.append(room.topic_id)

    if BannedUser.query.filter_by(topic_id=topic.uid).first() is not None:
        users = BannedUser.query.filter_by(topic_id=topic.uid).all()
        for u in users:
            if u.times_flagged >= 5 and u.topic_id != 1:
                print(u.topic_id)
                banned_users.append(
                    User.query.filter_by(uid=u.user_id).first().username)

    if Moderator.query.filter_by(user_id=user.uid).first() is not None:
        print("mod exists")
        mod_for = Moderator.query.filter_by(user_id=user.uid).all()
        for room in mod_for:
            print("mod")
            print(room.topic_id)
            if room.topic_id != 1:
                moderated_rooms.append(
                    Topic.query.filter_by(uid=room.topic_id).first().topicname)

    if topic is None:
        return redirect(url_for('chat'))

    if topic.uid in banned_from:
        return redirect(url_for('chat'))

    session['room'] = topic.topicname

    if 'email' not in session:
        return redirect(url_for('signin'))

    user = User.query.filter_by(email=session['email']).first()

    if user is None:
        return redirect(url_for('signin'))
    else:
        if request.method == 'POST':
            if form.validate() == False:
                return render_template('chat.html',
                                       form=form,
                                       topics=topics,
                                       users=users,
                                       messages=messages,
                                       banned_from=banned_from,
                                       moderated_rooms=moderated_rooms,
                                       banned_users=banned_users)
            else:
                uid = user.uid
                newtopic = Topic(form.topicname.data, uid)
                db.session.add(newtopic)
                db.session.commit()
                session['topic'] = newtopic.topicname
                newtopic = Topic.query.filter_by(
                    topicname=form.topicname.data).first()
                mod = Moderator(user.uid, newtopic.uid)
                db.session.add(mod)
                db.session.commit()
                return redirect('/chat/' + newtopic.topicname)

        if request.method == 'GET':
            return render_template('chat.html',
                                   form=form,
                                   topics=topics,
                                   users=users,
                                   messages=messages,
                                   banned_from=banned_from,
                                   moderated_rooms=moderated_rooms,
                                   banned_users=banned_users)