Example #1
0
def index():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live!','info')
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('index', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('index.html', title='Home', form=form,
                           posts=posts.items, next_url=next_url,
                           prev_url=prev_url)
Example #2
0
def edit(post_id):
    post = Post.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post.title = form.title.data
        post.content = form.content.data
        db.session.commit()
        flash('Your post has been edited!', 'success')
        return redirect(url_for('post', post_id=post_id))
    elif request.method == 'GET':
        form.title.data = post.title
        form.content.data = post.content
    return render_template('create_post.html',
                           title='Edytuj Post',
                           form=form,
                           legend='Edytuj Post')
Example #3
0
def updatepost(id):
    article = Articles.query.get_or_404(id)
    if article.author != current_user:
        abort(403)

    form = PostForm()
    if form.validate_on_submit():
        article.title = form.title.data
        article.category = form.category.data
        article.content = form.content.data
        db.session.commit()
        flash('Your post has been updated!', 'success')
        return redirect(url_for('post',id = article.id))
    elif request.method == 'GET':
        form.title.data = article.title
        form.category.data = article.category
        form.content.data = article.content
    return render_template('new_posts.html', title = 'Update post', form = form, legend = 'Update post')
Example #4
0
File: views.py Project: OQJ/myblog
def edit_post(id):
    post = Post.query.get_or_404(id)
    form = PostForm()

    form.title.data = post.title
    form.body.data = post.body
    form.tag.data = post.tag_id
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        tag = int(form.tag.data)
        post = Post(title=title, body=body, tag_id=tag)
        db.session.add(post)
        db.session.commit()
        flash('创建成功', 'success')
        return redirect(url_for('index'))

    return render_template('edit_post.html', form=form, post=post)
Example #5
0
def post_create():
    form = PostForm()
    if request.method == 'POST' and form.validate():
        new_post_author = form.author.data
        new_post_body = form.body.data

        new_post = {
            'author' : new_post_author,
            'body' : new_post_body,
        } 
        posts.append(new_post)
        flash('Post successfully created!')
        return redirect(url_for('posts_list'))

    return render_template(
        'post_create.html',
        form=form,
    )
Example #6
0
def paramInput():
	form = PostForm() 
	if form.validate_on_submit(): 
		print "title1: ",form.title.data , request.form.get('starttime'),request.form.get('code'),request.form.get('direction') #request.form.get('direction') 
		code = request.form.get('code')
		section2 = request.form.get('section2')
		spotID = section2[1:9]
		direction = request.form.get('direction')
		if direction == u'持有多头':
			direction =  u'LongHedging'
		else:
			direction =  u'ShortHedging'
		volume = form.title.data
		startdate = request.form.get('starttime') 
		enddate = request.form.get('endtime') 
		strategystartDate = request.form.get('strategystartDate') 
		period = form.content.data
		strategyName = request.form.get('strategyName') 
		strategyChoice = request.form.get('strategyChoice') 
		#导入用户数据库	
		param = {}
		code = code.encode('unicode-escape').decode('string_escape')
		code = code.split('.')[0]
		param['symbol'] = code
		param['spotID'] = spotID
		param['Qs'] = volume 
		param['period'] = period 
		param['direction'] = direction
		param['datastartdate'] = startdate # 数据日期
		param['startdate'] = strategystartDate # 策略日期
		param['enddate'] = enddate 
                param['strategyName'] = strategyName
		param['strategyChoice'] = strategyChoice
	        writeJson(param)
			
		total= strategyName	
		contents="\n策略命名:"+strategyName+"\n策略选择:"+strategyChoice +"\n合约代码:"+code+"\n现货数量:"+volume+"\nspotID:"+spotID+"\n调仓周期:"+period+"\n对冲方向:" \
		          +direction+"\n数据加载日期:"+startdate+"\n策略开始日期:"+strategystartDate+"\n结束日期:"+enddate
		post=Post(title=total,content = contents,user_id = current_user.id)
		db.session.add(post)
		db.session.commit()		
		print "finishing save data!!!!"
		flash(u'您的修改已经保存')
	return render_template('paramInput.html',title='paramInput',form=form)
Example #7
0
def edit_post(slug):
    """ Edits an existing blog entry """

    post = Post.query.filter_by(slug=slug).first()
    form = PostForm(obj=post)

    try:
        existing_hero = post.image[0]
    except IndexError:
        existing_hero = None

    if request.method == 'GET':
        # Set the select field (drop down menu) values for a get request.
        form.day.data = post.date_of_visit.strftime('%-d')
        form.month.data = post.date_of_visit.strftime('%-m')
        form.year.data = post.date_of_visit.strftime('%-Y')

    if form.validate_on_submit():
        form.populate_obj(post)

        post.date_of_visit = datetime(int(form.year.data),
                                      int(form.month.data), int(form.day.data))

        # Check if user has uploaded a new hero/banner image; and update.
        img_file = request.files['img_file']
        new_image = persist_img(img_file, form=form,
                                post=post) if img_file else None

        if new_image:

            # Check if an existing image is on disk and remove/replace.
            if existing_hero:
                # Remove hero image data from database
                db.session.delete(existing_hero)

                # Remove file from disk
                os.remove(existing_hero.abs_path)

            db.session.add(new_image)

        db.session.commit()
        return redirect(url_for('main.user', username=current_user.username))

    return render_template('create_post.html', title=post.title, form=form)
Example #8
0
def index():

    form = PostForm()
    if form.validate_on_submit():

        db.post.insert_one({
            'user_id' : current_user.id,
            'username' : current_user.username,
            'timestamp': datetime.utcnow().timestamp(),
            'body' : form.post.data
        })

        flash('Your post is live now!')
        return redirect(url_for('index'))

    offset = request.args.get('offset', 0, type=int)
    limit = app.config['POST_PER_PAGE']

    starting_id = db.post.find().sort('_id', pymongo.DESCENDING)
    last_id = starting_id[offset]['_id']

    leng = starting_id.count()

    if not offset + limit >= leng:
        next_url = '/index?offset=' + str(offset + limit)
    else:
        next_url = '/index?offset=' + str(leng - limit)

    if not offset - limit < 0:
        prev_url = '/index?offset=' + str(offset - limit)
    else:
        prev_url = '/index?offset=' + str(0)

    posts = current_user.followed_posts(last_id, limit)
    _posts = []

    for post in posts:

        art = {}
        art['author'] = {'username' : post['posts']['username']}
        art['body'] = post['posts']['body']
        _posts.append(art)    

    return render_template("index.html", title="Home", posts=_posts, form=form, next_url=next_url, prev_url=prev_url)
Example #9
0
def update(id):
    form = PostForm()
    posts = Post.query.filter_by(author = current_user).order_by(desc('timestamp'))
    if form.validate_on_submit():
        slug = Post.make_unique_slug(form.slug.data, id)
        if slug.strip() == '':
            slug = Post.slugify(form.title.data)

        post = Post.query.get(form.id.data)
        post.title = form.title.data
        post.slug = slug
        post.body = form.body.data
        post.timestamp = datetime.utcnow()
        db.session.commit()
        flash(gettext('Your post is updated!'))

        return redirect(url_for('user', nickname = current_user.nickname))

    else:
        post = Post.query.get(id)
        if post == None:
            flash(gettext('Post not found'))
            return redirect(redirect_url())

        if post.author.id != current_user.id or not current_user.is_authenticated:
            flash(gettext('You cannot update this post'))
            return redirect(redirect_url())

    form.id.data = id
    if form.title.data is None:
        form.title.data = post.title
        form.slug.data = post.slug
        form.body.data = post.body
    else:
        form.title.data = form.title.data
        form.slug.data = form.slug.data
        form.body.data = form.body.data

    return render_template('user.html',
        blog_name = app.blog_name,
        title = gettext('Profile'),
        user = current_user,
        form = form,
        posts = posts)
Example #10
0
def index():

    # 创建博文编辑表单
    form = PostForm()

    # 预校验博客正文
    if form.validate_on_submit():

        # 拿到用户编辑的博文
        content = form.content.data

        # 拿到当前用户(博主)
        user = current_user._get_current_object()
        # 插入博文对象,同时关联其博主
        post = Post(content=content, user=user)
        db.session.add(post)
        '''
        方式二:
        user = current_user._get_current_object()
        post = Post(content=content,user=user)
        user.posts.append(post)
        db.session.add(user)
        '''

        # 推送flash消息
        flash('发表成功!')

    # 展示所有内容
    # 拿到GET请求参数
    page = int(request.args.get('page', 1))

    # 获取分页器,内容按发布时间降序,每页5条,当前给出第3页数据,页码错误时不抛404而是返回第1页
    pagination = Post.query.order_by(Post.posttime.desc()).paginate(
        page=page, per_page=5, error_out=False)

    # 获得第3页的博文数据
    posts = pagination.items

    # 将编辑表单丢给页面渲染
    return render_template('main/index.html',
                           form=form,
                           posts=posts,
                           pagination=pagination,
                           page=page)
Example #11
0
File: admin.py Project: 0akarma/0aK
def edit_post(post_slug):
    form = PostForm()
    post = Post.query.filter_by(pslug=post_slug).first_or_404()
    if form.validate_on_submit():
        tags = form.tags.data
        tags = tags.split(";")
        for name in tags:
            tag = Tag.query.filter_by(tname=name).first()
            if tag is None:
                tag = Tag(tname=name, category_name=category)
                db.session.add(tag)
                db.session.commit()
            if tag not in post.tags:
                post.tags.append(tag)
                db.session.commit()

        post.ptitle = form.title.data
        post.pslug = form.slug.data
        post.timestamp = datetime.strptime(form.timestamp.data,
                                           '%Y-%m-%d %H:%M:%S')
        post.poster = form.poster.data
        post.desc = form.desc.data
        post.body = form.Body.data
        post.category_name = Category.query.get(form.category.data).cname
        lastmodified = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        post.lastmodified = datetime.strptime(lastmodified,
                                              '%Y-%m-%d %H:%M:%S')
        db.session.commit()
        flash('Post updated.', 'success')
        return redirect(url_for('blog.show_post', post_slug=post.pslug))
    form.title.data = post.ptitle
    form.slug.data = post.pslug
    form.timestamp.data = post.timestamp
    tags = ""
    for each in post.tags:
        tags = tags + ";" + each.tname
    tags = tags.lstrip(';')
    form.tags.data = tags
    form.poster.data = post.poster
    form.desc.data = post.desc
    form.Body.data = post.body
    form.category.data = post.category_name
    return render_template('admin/edit_post.html', form=form)
Example #12
0
def write_articles():
    if current_user.is_anony():
        return render_template('403.html')
    form = PostForm()
    if request.method == 'POST':
        title = request.form.get('title')
        body = request.form.get('body')
        ar = Article(content=body)
        db.session.add(ar)
        db.session.commit()
        ar = Article.query.filter_by(content=body).first()
        it = Items(title_or_ans=title,
                   author_id=current_user.id,
                   types=1,
                   art_id=ar.id)
        db.session.add(it)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('write_articles.html', form=form)
Example #13
0
def posts(username):
    form = PostForm()
    # url = url_for('static', filename='profile_pics/' + current_user.url)
    # query database for proper person
    person = User.query.filter_by(username=username).first()
    # when form is submitted appends to post lists, re-render posts page
    if form.validate_on_submit():
        # setting the name of the folder
        post_foldername = current_user.username
        # pointing to directory for user image folder
        img_path = os.path.abspath(
            os.path.dirname(__file__)) + '/static/images/'
        # making folder for each user
        if not os.path.exists(img_path + post_foldername):
            os.mkdir(img_path + post_foldername)

        # pointing to directory for images
        post_basedir = os.path.abspath(os.path.dirname(
            __file__)) + '/static/images/' + post_foldername + '/'

        # setting the name of image
        num = len(current_user.posts)
        post_filename = str(num) + '_post.png'
        # save pic
        url = post_basedir + post_filename
        form.pic.data.save(url)

        # resize with Pillow
        # im = Image.open(url)
        # Image.resize((100,100), Image.ANTIALIAS)
        # im.save(url)

        post = Post(desc=form.desc.data, user_id=current_user.id, url=url)
        # add post variable to database stage, then commit
        db.session.add(post)
        db.session.commit()
        flash('Your photo has been posted!.')
        return redirect(url_for('posts', username=username))
    return render_template('posts.html',
                           person=person,
                           title='Posts',
                           form=form,
                           username=username)
Example #14
0
def index():
    #insert a new post record into the database
    form = PostForm()
    if form.validate_on_submit():
        #save language for new posts
        language = guess_language(form.post.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        post = Post(body=form.post.data,
                    author=current_user,
                    language=language)
        db.session.add(post)
        db.session.commit()
        flash(_('Your post is now live!'))
        #standard practice to respond to a POST request generated by a web form submission
        #with a redirect - if the page is refreshed is will then prompt a GET request from
        #the data that was just submitted instead of resubmitting it
        #POST/REDIRECT/GET pattern
        return redirect(url_for('index'))
    #followed.posts methods returns a query object that grabs the posts the user is interested
    #in from the db. Calling all() triggeres the execution and will return all of the results

    #update -- followers association table to show amount of posts per page using the
    #paginate method query

    #requst.args parses the contents of the query string from the get method
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)

    #next url/prev url set to a url returned by url for
    #the url_for() function allows for keywords arguments to be added - refered in URL
    #directly or not, Flask will include as query argument
    next_url = url_for('index', page=posts.next_num) \
     if posts.has_next else None
    prev_url = url_for('index', page=posts.prev_num) \
     if posts.has_prev else None
    return render_template('index.html',
                           title='Home',
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
Example #15
0
def index(): #because the base page of websites is conventionally index.html? No! it's the '/'
    # user = {'username':'******'} # deprecated test user
    # posts list is a total hack to test site.
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live!')
        return redirect(url_for('index'))
    posts = current_user.followed_posts().all()
    # return render_template('index.html',user=user)
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index', page=posts.next_num) if posts.has_next else None
    prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None
    
    return render_template('index.html', title='Home', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
Example #16
0
def edit_post(id):
    """View function for edit_post."""

    post = Post.query.get_or_404(id)
    form = PostForm()

    if form.validate_on_submit():
        post.title = form.title.data
        post.text = form.text.data
        post.publish_date = datetime.datetime.now()

        # Update the post
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('blog.post', post_id=post.id))

    form.title.data = post.title
    form.text.data = post.text
    return render_template('edit_post.html', form=form, post=post)
Example #17
0
def index():
	form = PostForm()
	if form.validate_on_submit():
		post = Post(body=form.post.data, author=current_user)
		db.session.add(post)
		db.session.commit()
		flash(_('Your post is now live!'))
		return redirect(url_for('index'))
	# posts = current_user.followed_posts().all()

	page = request.args.get('page', 1, type=int)
	posts = current_user.followed_posts().paginate(page, app.config['POSTS_PER_PAGE'], False)
	next_url = url_for('index', page=posts.next_num) if posts.has_next else None
	prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None
	# url_for()函数有一个有趣的方面是你能够向它添加任何关键字参数,
	# 如果这些参数的名字没有直接在URL中引用,那么Flask会将它们作为查询参数包含在URL中

	return render_template('index.html', title='Home Page', form=form, posts=posts.items,
						   next_url=next_url, prev_url=prev_url)
Example #18
0
def post_edit(post_id):
    post = Post.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post.title = form.title.data
        post.body = form.body.data
        db.session.commit()
        flash('Twój post został pomyślnie edytowany', 'success')
        return redirect(url_for('post', post_id=post.id))
    elif request.method == 'GET':
        form.title.data = post.title
        form.body.data = post.body
    return render_template("admin.html",
                           title=post.title + "edit",
                           post=post,
                           form=form,
                           legend='Edytuj post')
Example #19
0
def createposts():
    post = PostForm()
    title = 'Kekembas Blog | Create Post'
    if request.method =='POST' and post.validate():
        post_title = post.title.data
        content = post.content.data
        user_id = current_user.id
        # print(post_title, content)
        # create new post instance
        new_post = Post(post_title, content, user_id)
        # add new post instance to database
        db.session.add(new_post)
        # commit
        db.session.commit()
        # flash a message
        flash("You have blabla", "success")
        # redirect back to create post
        return redirect(url_for('createposts'))
    return render_template('create_post.html', post=post, title=title)
Example #20
0
def post_update(post_id):
    post = Post.query.get_or_404(post_id)
    update_form = PostForm()
    if post.author.id != current_user.id:
        flash("You can't do this!", "danger")
        return redirect(url_for('myposts'))
    if request.method=='POST' and update_form.validate():

        post_title = update_form.title.data
        content = update_form.content.data

        post.title = post_title
        post.content = content

        db.session.commit()
        flash("You have changed your sh*t", 'info')
        return redirect(url_for('post_detail', post_id=post.id))

    return render_template('post_update.html', form=update_form, post=post)
Example #21
0
def user_post():
    form = PostForm()
    # ------------------------ Default Page View -----------------------------------------------------------------------
    if request.method == 'GET':
        return render_template('post.html', title='Post', form=form)
    # ------------------------ Post a New Post -------------------------------------------------------------------------
    if request.method == 'POST':
        # ------------------------ Successful Posting ------------------------------------------------------------------
        if form.validate_on_submit():
            post_obj = Post(body=form.body.data, author=current_user)
            db.session.add(post_obj)
            db.session.commit()
            flash('You post is not live!', 'success')
            return redirect(
                url_for('index')
            )  # prevent user from submit the form by refreshing the page
        # ------------------------ Failed Posting ----------------------------------------------------------------------
        else:
            return render_template('post.html', title='Post', form=form)
Example #22
0
File: admin.py Project: 0akarma/0aK
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        slug = form.slug.data
        category = Category.query.get(form.category.data).cname
        tags = form.tags.data

        title = form.title.data
        timestamp = datetime.strptime(form.timestamp.data, '%Y-%m-%d %H:%M:%S')
        desc = form.desc.data
        body = form.Body.data

        lastmodified = datetime.now()
        poster = form.poster.data

        post = Post(ptitle=title,
                    body=body,
                    desc=desc,
                    category_name=category,
                    pslug=slug,
                    poster=poster,
                    timestamp=timestamp,
                    lastmodified=lastmodified)
        # same with:
        # category_id = form.category.data
        # post = Post(title=title, body=body, category_id=category_id)
        tags = tags.split(";")
        db.session.add(post)
        db.session.commit()

        for name in tags:
            tag = Tag.query.filter_by(tname=name).first()
            if tag is None:
                tag = Tag(tname=name, category_name=category)
                db.session.add(tag)
                db.session.commit()
            if tag not in post.tags:
                post.tags.append(tag)
                db.session.commit()
        flash('Post created.', 'success')
        return redirect(
            url_for('blog.show_post', post_slug=post.pslug, toc=None))
    return render_template('admin/new_post.html', form=form)
Example #23
0
def create_post():
    form = PostForm()
    if form.validate_on_submit():
        # Find how many posts exist
        count = db.session.query(Post.post_id).count()
        # Create post object and add to db
        post = Post(post_id=count,
                    title=form.title.data,
                    subtitle=form.subtitle.data,
                    raw_body=form.raw_body.data,
                    tags=form.tags.data,
                    date=str(datetime.datetime.today().strftime("%B")) + ' ' +
                    str(datetime.datetime.today().day) + ', ' +
                    str(datetime.datetime.today().year))
        db.session.add(post)
        db.session.commit()
        flash('Posted!')
        return redirect(url_for('index'))
    return render_template('create_post.html', form=form, title='Make a Post')
Example #24
0
def index():
    form = PostForm()
    if form.validate_on_submit():
        language = guess_language(form.post.data)
        if language == "UNKNOWN" or len(language) > 5:
            language = ''
        post = Post(body=form.post.data, author=current_user, language=language)
        db.session.add(post)
        db.session.commit()
        flash(_("You have posted your tweet!!"))
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(page, app.config['POST_PER_PAGE'], False)
    next_page = url_for('index', page=posts.next_num) \
        if posts.has_next else None
    prev_page = url_for('index', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('index.html', title='Home', posts=posts.items, form=form, next_page=next_page,
                           prev_page=prev_page)
Example #25
0
def submit():
    form = PostForm()

    if form.validate_on_submit():

        p = Post(title=form.loc_name.data,
                 description=form.description.data,
                 Long=form.longitude.data,
                 Lat=form.latitude.data,
                 user_id=current_user.id)

        db.session.add(p)
        db.session.commit()

        flash('Location Submitted')

        return redirect(url_for('index'))

    return render_template('submit.html', title='Submit', form=form)
Example #26
0
def index():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live!')
        return redirect(url_for('index'))
    posts = [
        {
            'author': {'username': '******'},
            'body': 'Beautiful Thailand!'
        },
        {
            'author': {'username': '******'},
            'body': 'The Alita movie was so cool!'
        }
    ]
    return render_template('index.html', title='Home', form=form, posts=posts)
Example #27
0
def new_post():
    post_form = PostForm()
    if request.method == 'POST' and post_form.validate_on_submit():

        # Get form data
        title = post_form.title.data
        content = post_form.content.data

        # Create Post
        post = Post(title=title, content=content, author=current_user)
        db.session.add(post)
        db.session.commit()

        flash('Your post has been created', 'success')
        return redirect(url_for('blog.home'))
    return render_template("blog/create_post.html",
                           form=post_form,
                           title="New Post",
                           legend="New Article")
Example #28
0
def index():
    form = PostForm()

    if form.validate_on_submit():
        postsearch = Post.query.filter_by(
            problemName=form.problemName.data).first()
        post = Post(problemName=form.problemName.data,
                    problemLink=form.problemLink.data,
                    firstrating=form.tot.data,
                    tot=form.tot.data,
                    cnt=int(1),
                    rating=form.tot.data,
                    author=current_user)

        if postsearch is None:
            db.session.add(post)
            current_user.rate(post)
            db.session.commit()
            flash('Your rating has been added!')
            return redirect(url_for('index'))

        else:
            flash(
                'You can not add this problem because it has already been added.'
            )
            flash(
                'You can find this problem by going to this link: https://beautiful-problem.herokuapp.com'
                + '/problem/' + str(postsearch.id))
            return redirect(url_for('index'))

    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('index', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('index.html',
                           title='Home',
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
Example #29
0
def index():
    form = PostForm()

    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)

        db.session.add(post)
        db.session.commit()

        flash('Your post is now live!')

        return redirect(url_for('index'))

    posts = current_user.followed_posts().all()

    return render_template('index.html',
                           title='Home page',
                           form=form,
                           posts=posts)
def update_post(post_id):
    post = Post.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post.title = form.title.data
        post.content = form.content.data
        # só precisamos dar update, porque os dados já estão no banco de dados
        db.session.commit()
        flash('Your post has been update', 'success')
        return redirect(url_for('post', post_id=post.id))
    elif request.method == 'GET':
        form.title.data = post.title
        form.content.data = post.content
    return render_template('create_post.html',
                           title='Update Post',
                           form=form,
                           legend='Update Post')