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()
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')
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()
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')
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)
def topic_create(project_id): project = Project.query.get(project_id) if not current_user.in_team(project.team_id): abort(404) form = TopicForm(current_user, project, request.form.getlist('attachment')) if form.validate_on_submit(): topic = form.saveTopic() if topic is not None: flash(u'保存成功') return redirect(url_for('topic_detail', topic_id=topic.id)) else: flash(u'保存失败,请联系管理员', 'error') return render_template('project/topic_create.html', project=project, form=form)
def new(): form = TopicForm() flash(form.board_id.data) if form.validate_on_submit(): u = User.query.filter_by(id = g.user.id).first() topic = Topic(board_id=form.board_id.data, category=form.category.data, author=u, title=form.title.data, content=form.content.data) db.session.add(topic) db.session.commit() flash("发表成功") return redirect(request.args.get("next") or url_for("index")) form.board_id.data = request.args.get('board_id', '') return render_template('new.html', form = form, title = '新建')
def forum(page=1): # Нужная страница if request.args.get('page'): page = int(request.args.get('page')) # Разбиение на страницы pagination = Pagination(page, TOPIC_PER_PAGE, ForumTopic.query.count()) # Форма для постинга сообщений form_topic = TopicForm() form_message = MessageForm() # Если отправлена форма постинга if request.method == 'POST' and form_topic.validate_on_submit() and form_message.validate_on_submit(): # Данные из формы c применением форматирования data_topic = form_topic.topic.data data_message = message_format(form_message.message.data, True) # Создание темы и обновление счётчиков у пользователя new_topic = ForumTopic(name=data_topic, author_id=current_user.id) current_user.message_count += 1 current_user.topic_count += 1 db.session.add(new_topic) # Коммит в этом месте нужен, чтобы появился ID db.session.commit() # Создание сообщения new_mes = ForumMessage(topic_id=new_topic.id, author_id=current_user.id, text=data_message) db.session.add(new_mes) db.session.commit() return(redirect(url_for('topic', topic_id=str(new_topic.id)))) # Выборка всех тем с счётчиком сообщений для каждой # Подзапрос all_topics_subq = db.session.query( ForumMessage.topic_id, func.count(ForumMessage.id).label('mes_count')).\ group_by(ForumMessage.topic_id).\ subquery() # Основной запрос all_topics = db.session.query( ForumTopic, all_topics_subq.c.mes_count).\ join(all_topics_subq, ForumTopic.id == all_topics_subq.c.topic_id).\ order_by(ForumTopic.time_last.desc()).all() # Вернуть страницу return(render_template('forum.html', user=current_user, all_topics=all_topics, form_topic=form_topic, form_message=form_message, pagination=pagination))
def new_topic(): """ Starts a new thread creating a new Topic and corresponding first Post in the database. """ form = TopicForm(request.form) if form.validate_on_submit(): topic = Topic(subject=form.subject.data) post = Post(message=form.message.data, ip_address=request.remote_addr, name=form.name.data, email=form.email.data) topic.first_post = post post.topic = topic db.session.add(topic) db.session.commit() return redirect(url_for('view_topic', topic_id=topic.id)) return render_template('new_topic.html', form=form)
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))
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))
def topics(request): topic = TopicForm() topics = api_client.get(topic) return render(request, 'forum/topiclist.html', { 'topics': topics['objects'], 'meta': topics['meta'] })
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)
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)
def post(self): 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) topic.put_notifier() 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)
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})
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)
def post(self, topic_id): 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) topic.put_notifier() 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)
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)
def post(self, topic_id): if not self.has_permission: return topic = Topic.get(id=topic_id) if not topic: 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)
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})
def get(self): node_id = force_int(self.get_argument('node_id', 0), 0) node = Node.get(id=node_id) if node: selected = node.name else: selected = None choices = Node.get_node_choices() form = TopicForm.init(choices=choices, selected=selected) return self.render("topic/create.html", form=form, node=node)
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)
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))
def get(self, topic_id): topic = Topic.get(id=topic_id) if topic and (topic.author == self.current_user or self.current_user.is_admin): selected = topic.node.name else: return self.redirect_next_url() choices = Node.get_node_choices() args = {'node_name': [selected], 'title': [topic.title], 'content': [topic.content]} form = TopicForm.init(choices=choices, selected=selected, args=args) return self.render("topic/create.html", form=form, node=topic.node)
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') + "/")
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)
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
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")
def get(self, topic_id): if not self.has_permission: return topic = Topic.get(id=topic_id) if topic and (topic.author == self.current_user or self.current_user.is_admin): selected = topic.node.name else: return self.redirect_next_url() choices = Node.get_node_choices() args = {'node_name': [selected], 'title': [topic.title], 'content': [topic.content]} form = TopicForm.init(choices=choices, selected=selected, args=args) return self.render("topic/create.html", form=form, node=topic.node)
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))
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)
def get(self, topic_id): if not self.has_permission: return topic = Topic.get(id=topic_id) if topic: selected = topic.node.name else: return self.redirect_next_url() choices = Node.get_node_choices() args = {'node_name': [selected], 'title': [topic.title], 'content': [topic.content]} form = TopicForm.init(choices=choices, selected=selected, args=args) return self.render("topic/create.html", form=form, node=topic.node)
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, })
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)
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 })
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)
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})
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, })
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})
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)
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, })
def mail_write(reply=None): # Форма для нового сообщения form_recepient = RecepientForm() form_subject = TopicForm() form_message = MessageForm() # Если отправлена форма с новым сообщением if request.method == 'POST' and \ form_recepient.validate_on_submit() and \ form_subject.validate_on_submit() and \ form_message.validate_on_submit(): # Данные из формы c применением форматирования data_recipient = form_recepient.recepient.data data_subject = form_subject.topic.data data_message = message_format(form_message.message.data, True) # От кого и кому отправлено сообщение sender_id = current_user.id recipient_id = User.query.filter_by(login=data_recipient).first() if recipient_id: recipient_id = recipient_id.id else: return(render_template('info.html', user=current_user, text='No such user')) # Создание сообщений в отправленных у посылающего и # во входящих у того, кому адресовано письмо new_message = Mailbox(sender_id=current_user.id, owner_id=sender_id, directory=1, recipient_id=recipient_id, subject=data_subject, text=data_message, read=True) db.session.add(new_message) new_message = Mailbox(sender_id=current_user.id, owner_id=recipient_id, directory=0, recipient_id=recipient_id, subject=data_subject, text=data_message) db.session.add(new_message) db.session.commit() # Перейти в отправленные return(redirect(url_for('mailbox', box='sent'))) # Заполнение полей надо делать после проверки отправки, иначе # form_message.message.data останется =quote и не перезапишется # теми данными, которые ввёл пользователь # Если это ответное сообщение reply = request.args.get('reply') recepient = '' subject = '' if reply: previous_message = Mailbox.query.get(reply) recepient = previous_message.sender.login subject = 'Re: ' + previous_message.subject text = message_format(previous_message.text, False) quote = '' for line in text.split('\n'): if line[:3] == '>> ': quote += '>> ' + line + '\n' else: for i in range(0, len(line), 50): quote += '>> ' + line[i:i+50] + '\n' quote += '\n' form_message.message.data = quote # Все пользователей для выбора в качестве адреса all_users = User.query.all() return(render_template('mail_write.html', user=current_user, recepient=recepient, subject=subject, form_recepient=form_recepient, form_subject=form_subject, form_message=form_message, all_users=all_users))
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)
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, })
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 })