Пример #1
0
def post_update(post_id):
    post_instance = Post.query.get_or_404(post_id)
    if post_instance.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post_instance.title = form.title.data
        post_instance.description = form.description.data
        post_instance.body = form.body.data

        # inserisco il nome dell'immagine del db e controllo se l'immagine non è compromessa
        if form.image.data:
            try:
                image = save_picture(form.image.data)
                post_instance.image = image
            except Exception:
                db.session.commit()
                flash("Errore durante l'upload. Cambia immagine e riprova.")
                return redirect(
                    url_for('post_update', post_id=post_instance.id))

        db.session.commit()
        return redirect(url_for('post_detail', post_slug=post_instance.slug))
    elif request.method == "GET":
        form.title.data = post_instance.title
        form.description.data = post_instance.description
        form.body.data = post_instance.body

    post_image = post_instance.image or None

    return render_template("post_editor.html",
                           form=form,
                           post_image=post_image)
Пример #2
0
def editPost(id, name=None):
    form = PostForm()

    #Does post exist?
    post = Post.query.get_or_404(id)

    # update/alter database with new info
    if form.validate_on_submit():

        newTags = request.form.getlist('newTag[]')
        updatePost(form, post, get_db(), newTags, request.files)

    else:
        #get all tags associated with this post
        postTags = []
        for t in post.tags:
            postTags.append(t.name)
            #get all tags
            allTags = Tag.query.all()
            post.image = file_upload.get_file_url(post, filename="image")
            post.mobile_image = file_upload.get_file_url(
                post, filename="mobile_image")
            return render_template('blog/editPost.html',
                                   name=name,
                                   data=post,
                                   form=form,
                                   tags=postTags,
                                   allTags=allTags,
                                   current_year=current_year)
Пример #3
0
def post_update(post_id):
    post_instance = Post.query.get_or_404(post_id)
    if post_instance.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post_instance.title = form.title.data
        post_instance.description = form.description.data
        post_instance.body = form.body.data

        if form.image.data:
            try:
                image= save_picture(form.image.data)
                post_instance.image = image
            except Exception:
                db.session.commit()
                flash("C'è stao un problema con l'upload dell'immagine. Cambia immagine e riprova")
                return redirect(url_for('post_update', post_id=post_instance.id))

        db.session.commit()
        return redirect(url_for('post_detail', post_slug=post_instance.slug))
    elif request.method == "GET":
        form.title.data = post_instance.title
        form.description.data = post_instance.description
        form.body.data = post_instance.body
    return render_template("post_editor.html", form=form)
def post_update(post_id):
    post_instance = Post.query.get_or_404(post_id)
    #   verificare che l'user che ha creato il post e' lo stesso che sta 
    #   facendo la richiesta di aggiornamento, in caso negativo paginda di ERROR
    if post_instance.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post_instance.title = form.title.data
        post_instance.description = form.description.data
        post_instance.body = form.body.data

        if  form.image.data:
            try : # try in caso di image corrotta 
                print(form.image.data)
                image = save_picture(form.image.data) # return path
                post_instance.image = image
            except Exception:
                db.session.commit()
                flash("Si e' verifcato un problema con l'immagina caricata !!!")
                return redirect(url_for('post_update', post_id=post_instance.id))

        db.session.commit()
        # return redirect(url_for('post_detail', post_id=post_instance.id))
        return redirect(url_for('post_detail', post_slug=post_instance.slug))
    elif request.method == "GET" : 
        #   caso la pagina venga richiesta 
        #   e popolare il form
        form.title.data = post_instance.title
        form.description.data = post_instance.description
        form.body.data = post_instance.body
    # this row to show also image into editor preview
    post_image = post_instance.image or None
    return render_template("post_editor.html", form=form, post_image=post_image)
Пример #5
0
def post_create():
    form = PostForm()
    if form.validate_on_submit():
        slug = title_slugifier(form.title.data)
        new_post = Post(title=form.title.data,
                        body=form.body.data,
                        slug=slug,
                        description=form.description.data,
                        author=current_user)

        # inserisco il nome dell'immagine del db e controllo se l'immagine non è compromessa
        if form.image.data:
            try:
                image = save_picture(form.image.data)
                new_post.image = image
            except Exception:
                db.session.add(new_post)
                db.session.commit()
                flash("Errore durante l'upload. Cambia immagine e riprova.")
                return redirect(url_for('post_update', post_id=new_post.id))

        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('post_detail', post_slug=slug))
    return render_template("post_editor.html", form=form)
Пример #6
0
def edit_post(post_id=None):
    if page_data is None or page_data.pages == 1:
        page = 1
    else:
        page = page_data.page if page_data.page < page_data.pages or page_data.total % page_data.per_page != 1 else page_data.pages - 1
    form = PostForm()
    post = Post.query.get_or_404(post_id)
    if form.validate_on_submit():
        post.title = form.title.data
        post.body = form.body.data
        post.category = Category.query.get(form.category.data)
        post.read_num = form.read_num.data
        post.comment_num = form.comment_num.data
        post.like_num = form.like_num.data
        db.session.commit()
        flash('重新编辑成功!', 'ok')
        oplog = Oplog(
            user='******',
            ip=request.remote_addr,
            reason="编辑博客-%s" % form.title.data,
        )
        db.session.add(oplog)
        db.session.commit()
        return redirect(url_for('admin.post_list', page=page))
    form.title.data = post.title
    form.body.data = post.body
    form.category.data = post.category_id
    form.comment_num.data = post.comment_num
    form.read_num.data = post.read_num
    form.like_num.data = post.like_num
    return render_template('admin/edit_post.html', form=form)
Пример #7
0
def edit_post(post_id):
    """EDIT-POST page helps in editing of blog post."""
    post = Post.query.get(post_id)

    if post:
        form = PostForm(obj=post)
        if form.validate_on_submit():
            post.title = form.data.get("title")
            post.body = form.data.get("body")
            db.session.add(post)
            db.session.commit()
            flash("Post sucessfully edited.")
            return redirect(url_for("app.view_post", post_id=post_id))

        return render_template(
            "post.html",
            user=current_user,
            post=post,
            form=form,
            page_title="EDIT-POST",
            page_color="purple",
        )
    else:
        next_page = request.headers.get("Referer")
        flash("Blog post not found.")
        return redirect(next_page or url_for("app.home"))
Пример #8
0
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

        if form.image.data:
            img_file = save_picture(form.image.data, folder='images')
            post.image_file = img_file

        db.session.commit()
        flash('Post update', 'success')
        return redirect(url_for('post_detail', post_id=post_id))

    elif request.method == 'GET':
        # implicity GET
        form.title.data = post.title
        form.content.data = post.content
    return render_template('new_post.html',
                           title='Update Post',
                           form=form,
                           legend='Update Post')
Пример #9
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():

        session['content'] = request.form['content']
        html = markdown.markdown(request.form['content'],
                                 extensions=['nl2br'],
                                 safe_mode=True,
                                 output_format='html5')
        # Tags deemed safe
        allowed_tags = [
            'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li',
            'ol', 'pre', 'strong', 'ul', 'img', 'h1', 'h2', 'h3', 'p', 'br'
        ]
        # Attributes deemed safe
        allowed_attrs = {
            '*': ['class'],
            'a': ['href', 'rel'],
            'img': ['src', 'alt']
        }
        # Sanitize HTML
        html_sanitized = bleach.clean(bleach.linkify(html),
                                      tags=allowed_tags,
                                      attributes=allowed_attrs)
        post = Post(title=form.title.data,
                    content=html_sanitized,
                    author=current_user,
                    category=form.category_name.data)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created!', 'success')
        return redirect(url_for('home'))
    return render_template('newpost.html', title='New Post', form=form)
def post_create():
    form = PostForm()
    if form.validate_on_submit():
        slug = title_slugfier(form.title.data)
        new_post = Post(
            title=form.title.data, 
            body=form.body.data, 
            slug=slug,
            description=form.description.data,
            author=current_user)

        if  form.image.data:
            try : # try in caso di image corrotta 
                image = save_picture(form.image.data) # return path
                new_post.image = image
            except Exception:
                db.session.add(new_post)
                db.session.commit()
                flash("Si e' verifcato un problema con l'immagina caricata !!!")
                return redirect(url_for('post_update', post_id=new_post.id))

        db.session.add(new_post)
        db.session.commit()
        # return redirect(url_for("post_detail", post_id=new_post.id))
        return redirect(url_for("post_detail", post_slug=slug))
    # creare un nuovo post con un nuovo render html
    return render_template("post_editor.html", form=form)
Пример #11
0
def post_edit(post_id):
    # GET = view post, POST = edit post
    post = load_post(post_id)
    if post is None:
        abort(404, "Post not found")
    form = PostForm()
    if form.validate_on_submit():
        post.update(
            form.title.data, form.excerpt.data, form.body.data,
            datetime.combine(form.publish_date.data, datetime.min.time()))
        db.session.add(post)
        try:
            db.session.commit()
            return redirect(url_for("blog.post_view", post_id=post.id))
        except exc.IntegrityError:
            form.title.errors.append("Title already exists")
    form.title.data = post.title
    form.excerpt.data = post.excerpt
    form.body.data = post.body
    form.publish_date.data = post.pub_date
    return render_template('form.html',
                           form=form,
                           btn_label="Edit Post",
                           path=url_for("blog.post_edit", post_id=post.id),
                           method="post")
Пример #12
0
def post_create():
    form = PostForm()
    if form.validate_on_submit():
        slug = title_slugifier(form.title.data)
        new_post = Post(title=form.title.data,
                        body=form.body.data,
                        slug=slug,
                        description=form.description.data,
                        author=current_user)

        if form.image.data:
            try:
                image = save_picture(form.image.data)
                new_post.image = image
            except Exception:
                db.session.add(new_post)
                db.session.commit()
                flash(
                    "C'è stato un problema con l'upload dell'immagine. Cambia immagine e riprova."
                )
                return redirect(url_for('post_update', post_id=new_post.id))

        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('post_detail', post_slug=slug))
    return render_template("post_editor.html", form=form)
Пример #13
0
def new_post():
    form=PostForm()
    if form.validate_on_submit():
        post=Post(title=form.title.data,content=form.content.data,author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post created','success')
        return redirect(url_for('home'))
    return render_template('create_post.html',title='New Post',form=form)
Пример #14
0
def post():

    if session.get('user') is None:

        return redirect(url_for('login'))

    form = PostForm()

    categories = Category.query.all()

    if request.method == 'POST':

        if form.validate_on_submit():

            if form.category.data:

                category = form.category.data

            elif form.new_category.data:

                category = form.new_category.data
                new_category = Category(category)
                db.session.add(new_category)
                db.session.commit()

            else:

                return "Not Category Entered by User !!"

            title = form.title.data
            body = form.body.data

            #print("Category = {0}".format(category))

            #slug = slugify(title).encode('utf-8')
            slug = title
            author_id = Author.query.filter_by(name=session['user']).first().id
            category_id = Category.query.filter_by(
                name=str(category)).first().id
            blog_id = Blog.query.first().id
            publish_date = datetime.utcnow()

            #print('Slug = {0},Author ID = {1}, Category = {2}'.format(slug, author_id, category_id))

            post = Post(title, body, slug, blog_id, author_id, category_id,
                        publish_date)
            db.session.add(post)
            db.session.commit()

            return render_template('blog/post_helper.html',
                                   post=post,
                                   categories=categories)

    return render_template('author/post.html',
                           form=form,
                           categories=categories)
Пример #15
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title = form.title.data,
                    content = form.content.data,
                    author = users.get_current_user())
        post.put()
        flash('Post saved on database.')
        return redirect(url_for('list_posts'))
    return render_template('new_post.html', form=form)
Пример #16
0
def post():
    form = PostForm()
    tags_field = request.values.get('tags_field', '')

    if form.validate_on_submit():
        image_id = None

        # картинка
        if form.image.data:
            f = form.image.data
            image_id = str(uuid.uuid4())
            file_name = image_id + '.png'
            file_path = os.path.join(
                BLOG_POST_IMAGES_PATH, file_name
            )
            Image.open(f).save(file_path)
            # приведем изображение к рамзеру 600 на 300 pix
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 600, 'lg')
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 300, 'sm')
        # проверка есть ли искомая категория поста
        if form.new_category.data:
            new_category = Category(form.new_category.data)
            db.session.add(new_category)
            db.session.flush() #
            category = new_category
        else:
            category = form.category.data
 
        author = Author.query.get(session['id'])
        title = form.title.data.strip()
        body = form.body.data.strip()
        post = Post(
            author=author,
            title=title,
            body=body,
            image = image_id,
            category=category,
        )

        _save_tags(post, tags_field)

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

        slug = slugify(str(post.id) + '-' + post.title)
        post.slug = slug
        db.session.commit()

        flash('Сообщение опубликовано')
        return redirect(url_for('.article', slug=slug))

    return render_template('blog/post.html', form=form, 
                                             action="new", 
                                             tags_field=tags_field
                )  #action for editing    
Пример #17
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data, content=form.content.data, \
                    user_id=current_user.id) # or (author=current_user) back reference
        db.session.add(post)
        db.session.commit()
        flash(f'Post created.', 'success')
        return redirect(url_for('home_page'))

    return render_template('create_post.html', title='New Post', form=form)
Пример #18
0
def newPost():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('You have successfully made a post!', 'success')
        return redirect(url_for("home"))
    return render_template("newPost.html", form=form, legend='Create a Post')
Пример #19
0
def post():
    form = PostForm()
    tags_field = request.values.get('tags_field', '')

    if form.validate_on_submit():
        image_id = None

        if form.image.data:
            # process image
            f = form.image.data
            image_id = str(uuid.uuid4())
            file_name = image_id + '.png'
            file_path = os.path.join(BLOG_POST_IMAGES_PATH, file_name)
            Image.open(f).save(file_path)

            # create sizes
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 600, 'lg')
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 300, 'sm')

        if form.new_category.data:
            new_category = Category(form.new_category.data)
            db.session.add(new_category)
            db.session.flush()
            category = new_category
        else:
            category = form.category.data

        author = Author.query.get(session['id'])
        title = form.title.data.strip()
        body = form.body.data.strip()
        post = Post(author=author,
                    title=title,
                    body=body,
                    category=category,
                    image=image_id)

        # process tags
        _save_tags(post, tags_field)

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

        # do the slug
        slug = slugify(str(post.id) + '-' + post.title)
        post.slug = slug
        db.session.commit()

        flash('Article posted')
        return redirect(url_for('.article', slug=slug))

    return render_template('blog/post.html',
                           form=form,
                           action="new",
                           tags_field=tags_field)
Пример #20
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    user_id=current_user.id)
        db.session.add(post)
        db.session.commit()
        flash(f"Post Created", "success")
        return redirect(url_for('posts'))
    return render_template("create_post.html", form=form, title="New Post")
Пример #21
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        category_id = form.category.data
        post = Post(title=title, body=body, category_id=category_id)
        db.session.add(post)
        db.session.commit()
        flash('Post created.', 'success')
        return redirect(url_for('blog.show_post', post_id=post.id))
    return render_template('admin/new_post.html', form=form)
Пример #22
0
def new_post():
    # Craeting an instance of PostForm
    form=PostForm()
    #Check for a GET or POST request
    if form.validate_on_submit():
        post=Post(title=form.title.data,content=form.content.data,author=current_user)
        db.session.add(post)
        db.session.commit()
        #If successful display the message and redirect to the home page
        flash('Your post has been created!','success')
        return redirect(url_for('main'))
    return render_template('create_post.html',form=form)
Пример #23
0
def post():
    if not current_user.is_authenticated:  # 如果未登录则重定向到登录页
        flash('请先登录!')
        return redirect(url_for('login'))
    form = PostForm()
    if form.validate_on_submit():
        post = Post(form.title.data, form.content.data)
        post.author = current_user
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('post.html', pathname='post', form=form)
Пример #24
0
def new_post(): 
    form = PostForm()   
    if form.validate_on_submit():
        if form.picture.data:
            picture_file = save_picture_post(form.picture.data)
            post = Post(title=form.title.data, content=form.content.data, author=current_user, image_post = picture_file)
        else:    
            post = Post(title=form.title.data, content=form.content.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Blog created','success')
        return redirect(url_for('home'))
    return render_template('post.html',title='New Post', form=form, legend='Create Post')
Пример #25
0
def reply(post_id):
    post = Post.query.get_or_404(post_id)
    form = PostForm()
    if form.validate_on_submit():
        reply = Reply(title=form.title.data,
                      content=form.content.data,
                      writer=current_user,
                      original=post)
        db.session.add(reply)
        db.session.commit()
        flash('You have successfully added a post!', 'success')
        return render_template('post.html', post=post)
    return render_template("newPost.html", form=form, legend='Reply to a Post')
Пример #26
0
def create_activity():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Successfully submitted to Activity Office', 'success')
        return redirect(url_for('home'))
    return render_template("create_activity.html",
                           title="New Activity",
                           form=form)
Пример #27
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('home'))
    return render_template("create_post.html",
                           title="New Post",
                           form=form,
                           legend='New Post')
Пример #28
0
    def create_post(self):
        form = PostForm()
        if form.validate_on_submit():
            new_post = Post(title=form.title.data, content=form.content.data)
            db.session.add(new_post)
            for file in request.files.getlist("file"):
                pic = Photo(name=save_picture(file, "post_pics"),
                            post=new_post)
                db.session.add(pic)
            db.session.commit()
            flash('Post Has Been Added', 'success')
            return redirect('/admin/post')

        return self.render('admin/create_post.html', form=form)
Пример #29
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Ваш пост создан', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html',
                           title='Новый пост',
                           form=form,
                           legend='Новый пост')
Пример #30
0
def edit(slug):
    post = Post.query.filter_by(slug=slug).first_or_404()
    form = PostForm(obj=post)
    tags_field = request.values.get('tags_field', _load_tags_field(post))

    if form.validate_on_submit():
        original_image = post.image
        original_title = post.title
        form.populate_obj(post)

        if form.image.data:
            f = form.image.data
            image_id = str(uuid.uuid4())
            file_name = image_id + '.png'
            file_path = os.path.join(BLOG_POST_IMAGES_PATH, file_name)
            Image.open(f).save(file_path)

            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 600, 'lg')
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 300, 'sm')

            post.image = image_id
        else:
            post.image = original_image

        if form.new_category.data:
            new_category = Category(form.new_category.data)
            db.session.add(new_category)
            db.session.flush()
            post.category = new_category

            #if form.new_goverment.data:
            #    new_goverment = Goverment(form.new_goverment.data)
            #    db.session.add(new_goverment)
            #    db.session.flash()
            post.goverment = new_goverment

        if form.title.data != original_title:
            post.slug = slugify(str(post.id) + '-' + form.title.data)

        _save_tags(post, tags_field)

        db.session.commit()
        flash('Article edited')
        return redirect(url_for('.article', slug=post.slug))

    return render_template('blog/post.html',
                           form=form,
                           post=post,
                           action="edit",
                           tags_field=tags_field)
Пример #31
0
def edit_post(post_id):
    form = PostForm()
    post = Post.query.get_or_404(post_id)
    if form.validate_on_submit():
        post.title = form.title.data
        post.body = form.body.data
        post.category = Category.query.get(form.category.data)
        db.session.commit()
        flash('Post updated.', 'success')
        return redirect(url_for('blog.show_post', post_id=post.id))
    form.title.data = post.title
    form.body.data = post.body
    form.category.data = post.category_id
    return render_template('admin/edit_post.html', form=form)
Пример #32
0
def edit_post(slug):
	''' Post edit view of admin panel '''
	post = Post.objects(slug=slug)[0]
	form = PostForm(request.form, obj=post)
	if request.method == 'POST' and form.validate_on_submit():
		post.title = request.form.get('title')
		post.author = form.author.data
		if request.form.get('new_tags'):
			new_tags = process_tags(request.form['new_tags'])
			post.tags = new_tags
		post.index_background = form.index_background.data
		post.category = form.category.data
		post.published = form.published.data
		post.content = request.form.get('content')
		post.save()
		flash('Post has been edited')
		return redirect(url_for('posts.edit_post', slug=post.slug))

	return render_template("/admin/edit_post.html", form=form, slug=slug)
Пример #33
0
def new_post():
	''' Create new post from admin view. '''
	form = PostForm(request.form)
	if request.method == 'POST' and form.validate_on_submit():
		post_args = {}
		if Post.objects(title=form.title.data):
			flash("Post with this title already exists!")
			return render_template('/admin/new_post.html', form=form)
		if request.form.get('new_tags'):
			post_args['tags'] = process_tags(request.form.get('new_tags'))
		post_args['index_background'] = form.index_background.data
		post_args['published'] = form.published.data
		post_args['title'] = form.title.data
		post_args['author'] = form.author.data
		post_args['content'] = form.content.data
		post_args['category'] = form.category.data
		new_post = Post(**post_args)
		new_post.save()
		flash("New post, '{}', successfully created!".format(new_post.title))
		return redirect(url_for('posts.edit_post', slug=new_post.slug))
	return render_template('/admin/new_post.html', form=form)