Пример #1
0
def new(request):
    from board.utils import obj
    token = request.POST.get('token', None) or request.GET.get('token', None)
    old = dict(mongo.previews.find_one({'token': token})) if token else {}
    form = PostForm(request.POST, obj(old))
    if request.method == "POST" and form.validate():
        token = request.POST.get('token', token)
        job = {"title": form.title.data,
               "job_type": form.job_type.data,
               "date": datetime.datetime.now(),
               "description": form.description.data,
               "how_apply": form.how_apply.data,
               "email": form.email.data,
               "location": form.location.data,
               "url": form.url.data,
               "logo_url": form.logo_url.data,
               "company": form.name.data,
               "category": form.category.data,
               "token": token or uuid.uuid4().hex}
        if token:
            mongo.previews.update({'token': token}, job)
        else:
            mongo.previews.insert(job)
            if 'jobs' not in request.session:
                request.session['jobs'] = []
            request.session['jobs'].append(job['token'])
        return HttpResponseRedirect("%s?token=%s" % (reverse('preview'), job['token']))
    return {
        'form': form,
        'token': token}
Пример #2
0
async def _post(request, post_id=None):
    form = PostForm(request)
    form.status.data = int(form.status.data)

    post = None
    if post_id is not None:
        post = await Post.get_or_404(post_id)

    if request.method in ('POST', 'PUT') and form.validate():
        title = form.title.data
        assert str(form.author_id.data).isdigit()
        if post_id is None:
            post = await Post.filter(title=title).first()
        if not post:
            post = Post()
        tags = form.tags.data
        content = form.content.data
        is_page = form.is_page.data
        del form.tags
        del form.content
        del form.is_page
        form.populate_obj(post)
        post.type = Post.TYPE_PAGE if is_page else Post.TYPE_ARTICLE
        await post.save()
        await post.update_tags(tags)
        await post.set_content(content)
        ok = True
    else:
        ok = False
    post = await post.to_sync_dict()
    post['tags'] = [t.name for t in post['tags']]
    return json({'post': post if post else None, 'ok': ok})
Пример #3
0
def index():
    from models import Post, User
    from forms import PostForm

    if request.method == 'POST':
        print(request.form)
        form = PostForm(request.form)

        if form.validate():
            post = Post(**form.data)
            db.session.add(post)
            db.session.commit()

            flash('Post created!')
        else:
            flash('Form is not valid! Post was not created.')
            flash(str(form.errors))

    posts = Post.query.all()
    for post in posts:
        user_id = post.user_id
        user = User.query.filter_by(id=user_id).first()
        print(post.user_id, user)

        print(post.user)

    return render_template('home.txt', posts=posts)
Пример #4
0
def add_entry():
    form = PostForm()
    file = request.files["propics"]
    if "email" not in session:

        return redirect(url_for("home"))

    if request.method == "POST":
        if form.validate() == False:
            return render_template("welcome.html", form=form)
        else:

            g.post = db_session.query(User.id).filter(session["email"] == User.email).first()
            g.lastname = db_session.query(User.lastname).filter(session["email"] == User.email).first()
            g.firstname = db_session.query(User.firstname).filter(session["email"] == User.email).first()
            g.fullname = g.lastname + g.firstname

            file = request.files["propics"]
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
                # open(os.path.join(app.config['UPLOAD_FOLDER'], file), 'w').write(file)
                filename = filename

                entries = Post(form.subject.data, filename, form.body.data, user_id=g.post, author=g.fullname)
                # productimage = Image(form.body.data, filename)
                # db_session.add(productimage)
                db_session.add(entries)
                db_session.commit()
                flash("New entry was successfully posted")
            return redirect(url_for("show_entries"))

    return "It could go with the settings"
Пример #5
0
def members_only():
    form = PostForm(request.form)
    response = ""
    if request.method == "POST" and form.validate():
        id_post = form.id_post.data
        response = asyncio.run(post_handler.get_post(id_post))
    return render_template("posts.html", post=response, form=form)
Пример #6
0
  def post(self, board, thread, ajax=False):
    logging.info("post called")

    if not antiwipe.check(self.request.remote_addr):
      logging.warning("wipe redirect: %r" % self.request.remote_addr)
      return redirect("http://winry.on.nimp.org" )

    # validate post form
    form = PostForm(self.request.form)

    if not form.validate():
      return redirect("/%s/" % board)

    logging.info("data: %r" % form.data)
    logging.info("form: %r" % self.request.form)

    # if ok, save
    post, thread = save_post(self.request, form.data, board, thread)
    
    key = board + "%d" % post
    cookie = self.get_secure_cookie(key)
    cookie["win"] = key

    if ajax:
      return Response('{"post":%d }' % post)

    return redirect("/%s/%d/" % (board, thread))
Пример #7
0
def add_post():
    form = PostForm(request.form)
    if request.method == 'POST' and form.validate():
        title = form.title.data
        content = form.content.data

        # Create Cursor
        cur = mysql.connection.cursor()

        # Execute
        cur.execute(
            "INSERT INTO article(title, content, author) VALUES(%s, %s, %s)",
            (title, content, session['username']))

        # Commit to DB
        mysql.connection.commit()

        #Close connection
        cur.close()

        flash('Post Created', 'success')

        return redirect(url_for('dashboard'))

    return render_template('add_post.html', form=form)
Пример #8
0
def index():
    from forms import PostForm

    if request.method == 'POST':
        print(request.form)
        form = PostForm(request.form)
        if form.validate():
            post = Post(**form.data)
            db.session.add(post)
            db.session.commit()
            flash('Post created!')
        else:
            flash('Form is not valid! Post was not created.')
            flash(str(form.errors))

    posts = Post.query.all()
    # user = User.query.filter(id=posts[0].user_id)
    # user = posts[0].user

    for post in posts:
        user_id = post.user_id
        user = User.query.filter_by(id=user_id).first()
        print(user)
        #user = post.user

    return render_template('post_response.html', comments=None, posts=posts)
Пример #9
0
  def post(self, board, thread):
    logging.info("post called")

    ip = self.request.remote_addr

    qkey = "ip-%s" % ip
    quota = memcache.get(qkey) or 0
    quota += 1
    memcache.set(qkey, quota, time=POST_INERVAL*quota)

    logging.info("ip: %s, quota: %d" % (ip, quota))

    if quota >= POST_QUOTA:
      return redirect("http://winry.on.nimp.org" )

    # validate post form
    form = PostForm(self.request.form)

    if not form.validate():
      return redirect("/%s/" % board)

    # if ok, save
    logging.info("data valid %r" %( form.data,))
    post, thread = save_post(self.request, form.data, board, thread)
    
    key = board + "%d" % post
    cookie = self.get_secure_cookie(key)
    cookie["win"] = key

    return redirect("/%s/%d" % (board, thread))
Пример #10
0
def group_page(groupid):
    group = get_group(groupid)
    if not group:
        flash("Group does not exist.")
        return redirect(url_for('error'))
    owner = userid_to_object(group.groupownerid)
    #todo: make sure in_group method works
    if not in_group(session['userid'], groupid):
        flash("You can't view this page without joining the group.")
        return redirect(url_for('group_error', groupid=groupid))

    post_form = PostForm(request.form)
    pageid = get_pageid_group(groupid)

    if post_form.validate() and request.method == 'POST':
        post_on_page(pageid, session['userid'], post_form.content.data)
        return redirect(url_for('group_page', groupid=groupid))
    post_form = PostForm()
    posts = get_posts(pageid)

    return render_template('pages/grouppage.html',
                           form=post_form,
                           group=group,
                           owner=owner,
                           posts=posts,
                           page=pageid)
Пример #11
0
def edit_post(id):
    post_form = PostForm(request.form)
    if request.method ==  "POST" and post_form.validate():
        title = post_form.title.data
        body = post_form.body.data
        _id = post_form.id.data

        print("_id", _id)
        # Create Cursor
        cur = mysql.connection.cursor()
        # Interting POST
        cur.execute("UPDATE posts SET title = %s, body = %s WHERE id = %s ", (title, body, _id))
        # Commiting Transcation
        mysql.connection.commit()
        # Close Cursor
        cur.close()
        flash("Post Updated", "info")
        return redirect(url_for("dashboard"))
    # Create Cursor
    cur = mysql.connection.cursor()
    result = cur.execute("SELECT * FROM posts WHERE id = %s ", [id])
    if result > 0:
        post = cur.fetchone()
        post_form = PostForm(request.form, id=post['id'], title=post['title'], body=post['body'])
    return render_template("dashboard.html", form=post_form, edit_post=True)
Пример #12
0
def home():
    from models import Post

    if request.method == 'POST':
        form = PostForm(request.form)
        if form.validate():
            try:
                model = Post()
                form.populate_obj(model)
                db.session.add(model)
                db.session.commit()
                flash('Your post added!')
                return redirect(url_for('blog.home'))
            except Exception as ex:
                logger.error(ex)
                db.session.rollback()
                flash('Cant save post: ' + str(ex))
        else:
            logger.error('Someone have submitted an incorrect form!')
            flash('Invalid form. Please check fields')
    else:
        form = PostForm()

    return render_template('home.html',
                           form=form,
                           items=Post.query.all(),
                           comments_form=CommentForm())
Пример #13
0
def edit_post(post_id):
    post = post_repo.find(post_id)
    form = PostForm(request.form, post)
    if request.method == 'POST' and form.validate():
        form.populate_obj(post)
        post_repo.update(post)
        return redirect(url_for('show_post', post_id=post.id))
    return render_template('posts/edit.html', form=form, post=post)
Пример #14
0
def create_post():
    form = PostForm(request.form)

    if request.method == 'POST' and form.validate():
        post = post_repo.create(title=form.title.data, body=form.body.data)
        return redirect(url_for('show_post', post_id=post.id))
        
    return render_template('posts/new.html', form=form)
Пример #15
0
def add_post(channel):
    form = PostForm(request.form)
    if form.validate():
        post = Post(body = calculate_text(form.body.data))
        post.user_id = g.user.id
        post.channel_id = channel
        db.session.add(post)
        db.session.commit()
    return jsonify(result=1)
Пример #16
0
def index():
    form = PostForm(request.form)
    if form.validate():
        time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
        post = Post(body=form.post.data, title=form.title.data, timestamp=time)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('index'))
    posts = Post.query.all()
    return render_template("index.html", title='Home', posts=posts, form=form)
Пример #17
0
def post_create():
    if request.method == 'POST':
        p_form = PostForm(request.args)
        if p_form.validate():
            post = Post(**request.args)
            db.session.add(post)
            db.session.commit()
            return render_template('create_post.txt', post=post)
        else:
            return jsonify(p_form.errors)
Пример #18
0
def add_post():
    form = PostForm(request.form)
    if not form.validate():
        flash('Post title or content not valid')
        return redirect(url_for('view_posts'))
    item = Post(request.form['title'], request.form['body'])
    db.session.add(item)
    db.session.commit()
    flash('New post was added')
    return redirect(url_for('view_posts'))
Пример #19
0
def add_post():
   form=PostForm(request.form)
   if request.method=='POST' and form.validate():
      email=session['email']
      author=User.query.filter_by(email=email).first()
      new_post=Post(form.title.data,form.content.data,author.id)
      db.session.add(new_post)
      db.session.commit()
      return redirect(url_for('post_list'))
   else:
      return render_template('post.html',form=form)
Пример #20
0
def create_post():
    from models import Post
    from forms import PostForm

    if request.method == 'POST':
        form = PostForm(request.form)
    if form.validate():
        post = Post(**form.data)
        db.session.add(post)
        db.session.commit()
    return 'done'
Пример #21
0
def create():
    if request.method == 'POST':
        form = PostForm(request.form)
        if form.validate():
            post = form.save_post(Post(author=current_user))
            db.session.add(post)
            db.session.commit()
            flash('Post "%s" created successfully.' % post.title, 'success')
            return redirect(url_for('posts.detail', slug=post.slug))
    else:
        form = PostForm()
    return render_template('posts/create.html', form=form)
Пример #22
0
def edit_post(id):
   post=Post.query.get(id)
   user=User.query.get(post.author)
   if user.email!=session['email']:
      return "<h1>Unauthorized</h1>"
   form=PostForm(obj=post)
   if request.method=="POST" and form.validate():
      post.title=request.form['title']
      post.content=request.form['content']
      db.session.commit()
      return redirect(url_for('post_detail',id=id))
   return render_template("post.html",form=form)
Пример #23
0
def create_post():
    user = g.user
    form = PostForm()
    if request.method == 'POST' and form.validate():
        user_id = g.user.id
        file = form.image.data
        image = utilities.file_save(file, 'images')
        post = Post(title = form.title.data,body = form.body.data, image = image, timestamp = datetime.utcnow(), category = form.category.data, user_id = user_id, front_page = form.front_page.data )
        psc_db.session.add(post)
        psc_db.session.commit()
        flash('well posted mutafuqa')
        return redirect(url_for('pages.index'))
    return render_template("posts/create_post.html", title="write something", user =user, form = form)
Пример #24
0
def make_post():
    form = PostForm()

    if form.validate():
        post = Post(user_id=current_user.id,
                    text=form.text.data,
                    date_created=datetime.now())
        db.session.add(post)
        db.session.commit()

        return redirect(url_for('timeline'))

    return 'Something went wrong.'
Пример #25
0
def show_posts():
  form = PostForm(request.form)
  posts = list(Post.view('posts/by_date'))[::-1]
  errors = []
  if request.method == 'POST' and form.validate():
    new_post = make_post_from_request(request)
    g.db.save_doc(new_post)
    flash('New post was successfully created')
    return redirect(url_for('show_posts'))

  errors.extend(format_form_errors(form.errors.items()))
  return render_template \
    ('main.html', form = form, posts = posts, submit = 'Share', errors = errors)
Пример #26
0
def submit():
    form = PostForm(request.form)
    if request.method == "POST" and form.validate():
        #post_user = DBUser(username=current_user.name)
        post = DBPost(title=form.title.data,
                      text=form.text.data,
                      url=form.url.data,
                      submit_date=current_time(),
                      user_id=current_user.id)
        db.session.add(post)
        db.session.commit()

    return render_template("submit.html", form=form)
Пример #27
0
def add_post():
    form = PostForm(request.form)
    if request.method == 'POST' and form.validate():
        post = Post()
        form.populate_obj(post)
        post.author_id = g.user.id
        post.timestamp = datetime.utcnow()
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('show_post', post_id=post.id))
    return render_template('content_add_post.html',
                           title='Add post',
                           form=form,
                           user=g.user)
Пример #28
0
def post_index():
    form = PostForm()
    
    if g.is_logged_in == False:
        return redirect(url_for('signin'))

    if request.method == 'POST':
        if form.validate() == False:
            return redirect(url_for('post_index'))
        else:
            new_post = Post(body=form.body.data, timestamp=datetime.utcnow(), author=g.user)
            db.session.add(new_post)
            db.session.commit()
            return redirect(url_for('post_index'))
Пример #29
0
def edit_post(id):
  if not g.db.doc_exist(id):
    abort(404)

  form = PostForm(request.form)
  post = Post.get(id)
  errors = []

  if request.method == 'POST' and form.validate():
    post.title = form.title.data
    post.text = form.text.data
    post.tags = set(form.tags.data.split())
    post.save()
    flash('Post was successfully updated')
    return redirect(url_for('show_posts'))
  elif request.method == 'POST' and not form.validate():
    errors.extend(format_form_errors(form.errors.items()))
  elif request.method == 'GET':
    form.title.data = post.title
    form.text.data = post.text
    form.tags.data = ' '.join(post.tags)

  return render_template \
    ('edit_post.html', id = id, form = form, submit = 'Update', errors = errors)
Пример #30
0
def home():

    if request.method == 'POST':
        user = User.query.filter_by(username=current_user.username).first()
        form = PostForm(request.form)
        if form.validate():
            form.user = user
            post = Post(user=user, **form.data)
            db.session.add(post)
            db.session.commit()

    form = PostForm()

    visible_posts = Post.query.filter_by(is_visible=True).all()
    return render_template('home.html', form=form, posts=visible_posts)
Пример #31
0
def add_form():
    from forms import PostForm
    from models import Post
    if request.method == 'POST':
        form = PostForm(request.form)
        if form.validate():
            post = Post(**form.data)
            db.session.add(post)
            db.session.commit()
            return home()
        else:
            return str(form.errors), 400
    elif request.method == 'GET':
        return render_template('add_post.html')
    else:
        return 'bad method', 400
Пример #32
0
def home():

    if request.method == 'POST':
        user = User.query.filter_by(username=current_user.username).first()
        form = PostForm(request.form)
        if form.validate():
            form.user = user
            post = Post(user=user, **form.data)
            db.session.add(post)
            db.session.commit()

    form = PostForm()

    visible_posts = Post.query.filter_by(is_visible=True).all()
    return render_template(
        'home.html', form=form, posts=visible_posts)
Пример #33
0
def my_posts():
    form = PostForm()
    
    if g.is_logged_in == False:
        return redirect(url_for('signin'))

    if request.method == 'POST':
        if form.validate() == False:
            return redirect(url_for('my_posts'))
        else:
            new_post = Post(body=form.body.data, timestamp=datetime.utcnow(), author=g.user)
            db.session.add(new_post)
            db.session.commit()
            return redirect(url_for('my_posts'))
            
    user_posts = g.user.posts.filter_by(uid=g.user.uid).all()
    return render_template('my_posts.html', form=form, user_posts=user_posts)
Пример #34
0
def post():
    from models import Post, User
    from forms import PostForm

    if request.method == 'POST':
        print(request.form)
        form = PostForm(request.form)

        if form.validate():
            post = Post(**form.data)
            db.session.add(post)
            db.session.commit()

            flash('Post created!')
        else:
            flash('Form is not valid! Post was not created.')
            flash(str(form.errors))
Пример #35
0
def edit(slug):
    post = get_post_or_404(slug, author=None)
    if current_user == post.author:
        if request.method == 'POST':
            form = PostForm(request.form, obj=post)
            if form.validate():
                post = form.save_post(post)
                db.session.add(post)
                db.session.commit()
                flash('Post "%s" has been saved.' % post.title, 'success')
                return redirect(url_for('posts.detail', slug=post.slug))
        else:
            form = PostForm(obj=post)
    else:
        return redirect(url_for('posts.detail', slug=post.slug))

    return render_template('posts/edit.html', post=post, form=form)
Пример #36
0
def add_post():
    post_form = PostForm(request.form)
    if request.method ==  "POST" and post_form.validate():
        title = post_form.title.data
        body = post_form.body.data
        author = session['name']
        # Create Cursor
        cur = mysql.connection.cursor()
        # Interting POST
        cur.execute("INSERT INTO posts(title, body, author, create_date) VALUES(%s, %s, %s, curdate())", (title, body, author))
        # Commiting Transcation
        mysql.connection.commit()
        # Close Cursor
        cur.close()
        flash("Post Saved", "info")
        return redirect(url_for("dashboard"))
    return render_template("dashboard.html", form=post_form, add_post=True)
Пример #37
0
def new_post():
    if request.method == 'POST':
        user = User.query.filter_by(username=current_user.username).first()
        form = PostForm(request.form)
        if form.validate():
            print(type(user))
            form.user = user
            post = Post(user=user, **form.data)
            db.session.add(post)
            db.session.commit()
            post_title = Post.query.filter_by(title=post.title).first().title
            flash('Post "{}" created!'.format(post_title))
            return redirect(url_for('blog.home'))

    form = PostForm()

    return render_template('new_post.html', form=form)
Пример #38
0
async def _post(request, post_id=None):
    form = PostForm(request)
    msg = ''

    if post_id is not None:
        post = await Post.get_or_404(post_id, sync=True)

    if request.method == 'POST' and form.validate():
        title = form.title.data
        assert str(form.author_id.data).isdigit()
        post = await Post.filter(title=title).first()
        if post:
            await post.save()
            msg = 'Post was successfully updated.'
        else:
            post = Post()
            msg = 'Post was successfully created.'
        form.status.data = form.status.data == 'on'
        tags = form.tags.data
        content = form.content.data
        is_page = form.is_page.data
        del form.tags
        del form.content
        del form.is_page
        form.populate_obj(post)
        if is_page:
            post.type = Post.TYPE_PAGE
        await post.save()
        await post.update_tags(tags)
        await post.set_content(content)
        context = await _get_post_context()
        return await render_template('admin/list_posts.html', request, context)
    elif post_id is not None:
        form = PostForm(request, obj=post)
        form.tags.data = [tag.name for tag in post.tags]
        form.can_comment.data = post.can_comment
        form.is_page.data = post.is_page
        form.status.data = 'on' if post.status else 'off'
        form.submit.label.text = 'Update'

    tags = await Tag.all()
    authors = await User.all()
    return await render_template('admin/post.html', request,
                                 {'form': form, 'msg': msg, 'post_id': post_id,
                                  'tags': tags, 'authors': authors})
Пример #39
0
    def post(self):
        form = PostForm()

        if form.validate_on_submit():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                remain = request.values.get('remain', False, bool)
                post = Post.create()
                form.populate_obj(post)
                post.user = current_user

                f = request.files.get('file')

                if f:
                    picture = Picture.create()
                    picture.save_file(f, current_user)
                    post.cover_picture_id = picture.id if picture else 0

                # init the score
                post.update_score(page_view=1)

                post.editor_version = 1
                post.save()

                Feed.clear_feed_cache()

                if post.is_draft:
                    message = _('POST_DRAFT_SAVE_SUCESS')
                else:
                    message = _('POST_PUBLIC_SAVE_SUCESS')

                if remain:
                    url = url_for('PostsView:put', id=post.id, remain='y')
                else:
                    url = url_for('PostsView:get', id=post.id)

                return render_view(url, redirect=True, message=message)

            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/posts/edit.html',
                           form=form)
Пример #40
0
def view_topic(topic_id):
    """
    Displays a Topic with all its posts.
    :param topic_id:
    :type topic_id: int
    """
    topic = Topic.query.filter_by(id=topic_id).first()
    if not topic:
        abort(404)
    form = PostForm(request.form)
    if request.method == 'POST':
        if form.validate():
            post = Post(message=form.message.data, ip_address=request.remote_addr, name=form.name.data,
                        email=form.email.data)
            post.topic = topic
            db.session.commit()
        return redirect(url_for('view_topic', topic_id=topic_id))
    return render_template('topic.html', topic=topic, form=form)
Пример #41
0
def new_post():
    if request.method == 'POST':
        user = User.query.filter_by(username=current_user.username).first()
        form = PostForm(request.form)
        if form.validate():
            print(type(user))
            form.user = user
            post = Post(user=user, **form.data)
            db.session.add(post)
            db.session.commit()
            post_title = Post.query.filter_by(title=post.title).first().title
            flash('Post "{}" created!'.format(post_title))
            return redirect(url_for('blog.home'))

    form = PostForm()

    return render_template(
        'new_post.html', form=form)
Пример #42
0
def finish_edit_post():
    item = None
    if 'current_post' in session:
        item = Post.query.get(session.get('current_post'))
    if item is None:
        session.pop('current_post', None)
        flash('Post was not found')
        return redirect(url_for('view_posts'))
    form = PostForm(request.form)
    if not form.validate():
        session.pop('current_post', None)
        flash('Post title or content not valid')
        return render_template('view_post.html', post=item)
    item.title = request.form['title']
    item.body = request.form['body']
    db.session.commit()
    session.pop('current_post', None)
    flash('Post was updated')
    return render_template('view_post.html', post=item)
Пример #43
0
def edit_post(post_id):
    # To edit a post, if GET check author and populate form,
    # if POST check author and update
    post = Post.query.filter_by(id=post_id).first()
    if ((post.author.id == g.user.id) or g.user.role == ROLE_ADMIN):
        form = PostForm(request.form, obj=post)
        if request.method == 'POST' and form.validate():
            form.populate_obj(post)
            db.session.add(post)
            db.session.commit()
            return redirect(url_for('show_post', post_id=post.id))

        return render_template('content_add_post.html',
                               title=post.title,
                               form=form,
                               user=g.user,
                               edit=post_id)

    return redirect(url_for('index'))
Пример #44
0
def main():
    from models import Post, Comment
    from forms import PostForm

    if request.method == 'GET':
        posts = Post.query.all()

        return render_template('home.html', posts=posts)

    if request.method == 'POST':
        form = PostForm(request.form)
        if form.validate():
            post = Post(**form.data)
            db.session.add(post)
            db.session.commit()
            flash('A very good Post number {} was added'.format(post.id))
            return render_template('flash_page.html'), 200
        else:
            flash('Something wrong! {}'.format(str(form.errors)))
            return render_template('flash_page.html'), 403
Пример #45
0
def welcome():
    form = PostForm()

    if request.method == "POST":
        if form.validate() == False:

            return render_template("welcome.html", entries=entries)
        else:
            session["email"] = form.email.data

    elif request.method == "GET":
        import psycopg2

        conn = psycopg2.connect("dbname='mydatabase' user='******' host='localhost' password='******'")
        cur = conn.cursor()
        cur.execute("""select subject, simage, body, author, timestamp from posts order by uid desc""")
        rows = cur.fetchall()

        entries = [dict(subject=row[0], simage=row[1], body=row[2], author=row[3], timestamp=row[4]) for row in rows]
        return render_template("welcome.html", entries=entries, form=form)
Пример #46
0
def modify(postId):
    post = Post.query.get(postId)
    form = PostForm()
    user = g.user
    if request.method == 'POST' and form.validate():
        post.title = form.title.data
        post.body = form.body.data
        post.category = form.category.data
        post.front_page = form.front_page.data
        if form.image.data:
            file = form.image.data
            post.image = utilities.file_save(file,'images')
        psc_db.session.add(post)
        psc_db.session.commit()
        return redirect(url_for('posts.manage_posts'))
    form.title.data = post.title
    form.body.data = post.body
    form.category.data = str(post.category)
    form.front_page.data = post.front_page
    return render_template("posts/create_post.html", user = user, form = form)
Пример #47
0
def post_add_edit(id=None):

    if id is None:
        # add
        form=PostForm(request.form)
        post=Post()
    else:
        # edit
        post=db_session.query(Post).filter_by(id=id).first()
        if post is None:
            abort(404)
        form=PostForm(request.form, obj=post)        

    if request.method=='POST' and form.validate():
        form.populate_obj(post)
        db_session.add(post)
        db_session.commit()
        return redirect(url_for('index'))

    return render_template('add_edit.html',
                           form=form,
                           id=id)
Пример #48
0
def index():
    from models import Post
    from forms import PostForm

    # Добавление поста
    if request.method == 'POST':
        form = PostForm(request.form)

        if form.validate():
            post = Post(**form.data)
            db.session.add(post)
            db.session.commit()

            flash('Пост опубликован.')

        else:
            flash('Форма не валидна! Пост не был опубликован.')

    posts = Post.query.all()

    # Вывод всех постов
    return render_template('show_posts.html', posts=posts)
Пример #49
0
def index():
    from models import Post, Comment
    from forms import PostForm

    if request.method == 'POST':
        print(request.form)
        form = PostForm(request.form)

        if form.validate():
            post = Post(**form.data)
            db.session.add(post)
            db.session.commit()

            flash('Post created!')

    posts = Post.query.all()
    for post in posts:
        print(post.author, post.title)

        print(post.content)

    return render_template('index.html', posts=posts)
Пример #50
0
  def post(self, board, thread):
    if not re.match('^\w+$', board):
      raise NotFound

    self.person()  # move to MW?

    ip = obfuscate_ip(self.request.remote_addr)
    if not antiwipe.check(self.p, ip=ip, board=board, thread=thread):
      logging.warning("wipe redirect: %r" % self.request.remote_addr)
      return redirect_out()

    # enforce 733t m0d3
    if self.NEWFAG and \
            not self.p.get("postcount") > self.OLDFAG and \
            (board,thread) not in self.NEWFAG and \
            thread == 'new':
        board += u'~'

        logging.warning("why so newfag?")

    # validate post form
    form = PostForm(self.request.form)

    if not form.validate():
      logging.info("form errors: %r" % form.errors)
      return self.response_error(form.errors, board)

    # if ok, save
    post, thread = save_post(self.request, form.data, board, thread, self.request.remote_addr)
    
    key = board + "%d" % post
    cookie = self.get_secure_cookie(key)
    cookie["win"] = key

    if not self.NEWFAG or (board,thread) not in self.NEWFAG:
        self.p["postcount"] += 1

    return self.response_ok(board, thread, post)
Пример #51
0
def save_post(post_id=None):
    """Save Post to database

    If post_id is None a new Post will be inserted in the database. Otherwise
    the existing Post will be updated.
    """
    message = 'Post updated'
    orig_tags = []

    post_form = PostForm(request.form)

    if not post_form.validate():
        flash('ERROR: errors detected. Post NOT saved!', category='error')
        return edit_post(post_id=post_id, post_form=post_form)

    # test if we're creating a new post, or updating an existing one
    if post_id is None:
        post = Post()
        post.status_id = 1
        post.user_id = session['user_id']
        post.createdate = datetime.now()
    else:
        post = get_post(post_id)
        orig_tags = [tag for tag in post.tags]

    post_form.populate_obj(post)
    post.lastmoddate = datetime.now()

    # compile input to html
    post.compile(app.config['REPL_TAGS'])

    # update pubdate if post's pubdate is None and its status is set
    # to public
    if request.form['status'] == 'public' and \
           unicode(post.status) != 'public' and \
           post.pubdate is None:
        post.pubdate = datetime.now()

    post.status = get_status(request.form['status'])

    if post.slug is None:
        post.slug = slugify(post.title)

    if post_id is None:
        db_session.add(post)
        message = 'New post was successfully added'

    db_session.commit()

    for tag in orig_tags:
        recalculate_tagcount(tag)

    for tag in post.tags:
        if tag not in orig_tags:
            recalculate_tagcount(tag)

    db_session.commit()

    flash(message, category='info')

    return redirect(url_for('edit_post', post_id=post.id))
Пример #52
0
    def put(self, id):
        post = Post.get_by_id(id)

        if post is None or not post.can_edit() or post.is_hidden:
            return render_view(url_for('PostsView:index'),
                               status=False,
                               redirect=True,
                               message=_('POST_NOT_FOUND'))

        form = PostForm(post=post)

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                cover_picture_id = request.values.get('cover_picture_id', 0, int)
                is_draft = request.values.get('status', 0, int) == Post.POST_DRAFT
                remain = request.values.get('remain', False, bool)

                if post.cover_picture and cover_picture_id == 0:
                    # remove the picture, when user request its deletion
                    post.cover_picture.remove()

                form.populate_obj(post)

                f = request.files.get('file')

                if f:
                    if post.cover_picture:
                        post.cover_picture.remove()
                    picture = Picture.create()
                    picture.save_file(f, current_user)
                    post.cover_picture_id = picture.id if picture else 0

                if is_draft:
                    post.status = Post.POST_DRAFT
                else:
                    if post.save_count == 1 or post.created_at is None:
                        post.created_at = Post.current_date()
                        post.save_count = 1
                    post.status = Post.POST_PUBLIC
                    post.save_count += 1

                post.editor_version = 1
                post.save()

                Feed.clear_feed_cache()

                if post.is_draft:
                    message = _('POST_DRAFT_SAVE_SUCESS')
                else:
                    message = _('POST_PUBLIC_SAVE_SUCESS')

                if not remain:
                    return render_view(url_for('PostsView:get', id=post.id),
                                       redirect=True,
                                       message=message)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/posts/edit.html',
                           form=form,
                           post=post)