def create_post(): form = PostForm(request.form) if 'username' in session: if request.method == 'POST' and form.validate_on_submit(): try: post = Post(title=form.title.data, preview=form.preview.data, body=form.body.data, author=session['username']) tag_list = re.sub(r'[\s, .]', ' ', form.tags.data).split() for i in set(tag_list): if Tag.query.filter_by(name=i).first(): tag = Tag.query.filter_by(name=i).first() else: tag = Tag(name=i) post.tags.append(tag) post.author = session['username'] if request.form['submit'] == 'draft': post.visible = False db.session.add(post) db.session.commit() flash('Post create') except Exception as e: print(f'Something wrong\n{e.__class__}') raise e return redirect(url_for('posts.index')) elif not form.validate_on_submit(): print('validate: ', form.validate_on_submit()) else: return redirect('/log_in') return render_template('create_post.html', form=form)
def post_book(): form = PostForm() if form.validate_on_submit(): current_writer_name = form.book_writer.data.title() current_title_name = form.book_title.data.title() if BookWriter.query.filter_by(book_writer = current_writer_name).first() == None: current_writer = BookWriter(book_writer = form.book_writer.data.title()) db.session.add(current_writer) flash('New writer is added.') else: current_writer = BookWriter.query.filter_by(book_writer = current_writer_name).first() if BookTitle.query.filter_by(book_title = current_title_name).first() == None: current_title = BookTitle(book_title = form.book_title.data.title(), timestamp = datetime.utcnow(), author = g.user) db.session.add(current_title) flash('Your book is posted!') else: current_title = BookTitle.query.filter_by(book_title = current_title_name).first() flash('This book was posted earlier.') current_writer.add_composed(current_title) db.session.add(current_writer) db.session.commit() return redirect(url_for('index')) return render_template('post_book.html', form = form)
def update_post(post_id): cur = mysql.connection.cursor() cur.callproc("GETPOST_BY_ID", [post_id]) post = cur.fetchone() cur.close() if post['username'] != session['username']: abort(403) form = PostForm() if form.validate_on_submit(): cur = mysql.connection.cursor() cur.callproc("UPDATE_POSTS", [ post['post_id'], form.Title.data, form.Content.data, form.Description.data ]) #cur.stored_results() mysql.connection.commit() # cur.close() flash(f'Post updated successfully', 'success') return redirect(url_for('post', post_id=post['post_id'])) elif request.method == 'GET': form.Title.data = post['title'] form.Content.data = post['content'] form.Description.data = post['post_description'] return render_template('Create_post.html', title='Update Post', form=form, legend='Update Post')
def publish_page(): db = current_app.config["db"] categories = [ x[0] for x in db.get_category_names()] colors = ['black', 'white', 'red', 'orange', 'yellow', 'green', 'blue', 'purple', 'multicolor'] form = PostForm() form.category.choices = categories form.color.choices = colors if form.validate_on_submit(): cat = form.category.data col = form.color.data situation = request.form.get('situation') #checkbox newItem = Item(title=form.title.data,description=form.description.data, category=cat) newItem.color = col newItem.situation = situation if form.picture.data: pic = save_picture(form.picture.data) db.add_item_image(newItem, pic) #save item to item table ###create post neden title ismini alıyor ki bunu düzelt tag1 = form.tag1.data # tag2 = form.tag2.data # db.create_post(current_user.username,form.title.data,tag1,tag2) #flash('Your post has been created!', 'success') return redirect(url_for('home_page')) return render_template("publish.html", form=form)
def post_form(): form = PostForm() global numposts if form.validate_on_submit(): total = form.total.data content = form.content.data post_object = { "author": current_user.name, "content": content, "total": total } numposts += 1 new_tx_address = "{}/new_transaction".format(CONNECTED_NODE_ADDRESS) requests.post(new_tx_address, json=post_object, headers={'Content-type': 'application/json'}) return redirect(url_for('post_form')) return render_template('admin/post_form.html', form=form)
def add_post(): """ users will be directed to the posting page """ check_status() add_post = True author_id = current_user.id form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, post_body=form.post_body.data, author_id=author_id) db.session.add(post) db.session.commit() flash( 'This blog post has been published successfuly, but will be made public once reviewed' ) # return redirect('blog_user.add_post') return render_template('bloguser/posts.html', add_post=add_post, form=form, title='Posts')
def post(): form = PostForm() if request.method == 'GET': if request.args.get('isbn'): form.isbn.data = request.args.get('isbn') if form.validate_on_submit(): isbn = form.isbn.data.strip().replace('-','').replace(' ','') price = form.price.data if price == '': price = None cond = form.condition.data comments = form.comments.data courses = form.courses.data.strip().replace(' ','').upper() if len(courses) > 9: courses = '' if not Book.query.get(isbn): info = get_amazon_info(isbn) image = get_amazon_image(isbn) b = Book(isbn=isbn, title=info['title'], author=info['author'], amazon_url=info['url'], image=image, courses=[courses]) add_commit(db, b) else: b = Book.query.get(isbn) old_courses = list(b.courses) old_courses.append(courses) b.courses = list(set(old_courses)) db.session.commit() p = Post(uid=current_user.id, timestamp=datetime.utcnow(), isbn=isbn, price=price,condition=cond,comments=comments) add_commit(db, p) email_subbers(p) return redirect(url_for('book',isbn=isbn)) return render_template('post.html', post_form = form)
def user(nickname, page = 1): user = User.query.filter_by(nickname=nickname).first() form = PostForm() if form.validate_on_submit(): post = Post(body = form.post.data, timestamp = datetime.utcnow(), user = g.user, to_user = user) db.session.add(post) db.session.commit() flash('Your post is now live!', 'success') return redirect(url_for('user', nickname=user.nickname, page=page)) if user == None: flash('User ' + nickname + ' not found.', 'warning') return redirect(url_for('index')) posts = user.followed_posts().paginate(page, POSTS_PER_PAGE, False) return render_template( "site/%s/user.html" % (cordon.config['TEMPLATE']), user=user, posts=posts, form=form, SHOW_COMMENT_FORM = False, )
def post_prayer(): form = PostForm() group_forms = [(group, GroupPost(prefix = str(group.id))) for group in g.user.groups] if form.validate_on_submit(): language = guessLanguage(form.post.data) if language == 'UNKNOWN' or len(language) > 5: language = '' post = Post(subject = form.subject.data, body = form.post.data, timestamp = datetime.utcnow(), author = g.user, language = language, public = form.public.data) db.session.add(post) db.session.commit() if not post.public: # Filter only group that were selected. add_groups = filter(lambda g: g[1].group_access.data == True, group_forms) for group in add_groups: group[0].add_post(post) db.session.add(group[0]) db.session.commit() flash(gettext('Your post is now live!')) return redirect(url_for('post', id = post.id)) return render_template('post_form.html', title = 'Post Prayer', form = form, group_forms = group_forms)
def edit_post(id, page = 1): post = Post.query.get(id) if post == None: flash('Post not found.') return redirect(url_for('index')) if post.author.id != g.user.id: flash('You cannot edit this post.') return redirect(url_for('index')) form = PostForm() if form.validate_on_submit(): language = guessLanguage(form.post.data) if language == 'UNKNOWN' or len(language) > 5: language = '' post.subject = form.subject.data post.body = form.post.data post.language = language db.session.add(post) db.session.commit() flash(gettext('Your post has been updated!')) return redirect(url_for('index')) elif request.method != "POST": form.subject.data = post.subject form.post.data = post.body comments = post.comments.order_by(Comment.timestamp.desc()).paginate(page, POSTS_PER_PAGE, False) return render_template('edit_post.html', post = post, form = form, comments = comments)
def edit_post(id): form = PostForm() if users.is_current_user_admin() and form.validate_on_submit(): tags = Tags() categories = Categories() updating_post = BlogPost.get(int(id)) title = request.json['title'] body = request.json['body'] raw_category = request.json['category'] editing_tags = request.json['tags'] raw_summary = request.json['summary'] tags_keys = tags.update(editing_tags, updating_post) category_key = categories.update(raw_category, updating_post.category) updating_post.edit(title, body, datetime.now(), tags_keys, category_key, raw_summary, raw_answers=request.json['answers']) return jsonify(updating_post.to_json()) # dangerous
def newPost(): available_posts = db.session.query(Category).all() post_list = [(i.id, i.name) for i in available_posts] form = PostForm() form.category.choices = post_list if form.validate_on_submit(): picture_file = save_picture(form.image.data) article = Article(name=form.title.data, description=form.content.data, image=picture_file, image_desc=form.image_description.data, kanji=form.kanji.data, kana=form.kana.data, image_safeDesc=form.image_safe.data) article.category_id = form.category.data db.session.add(article) db.session.commit() flash('Dodano nowy artykuł!', 'success') return redirect(url_for('handle_articles')) return render_template('newPost.html', title='Nowy artykuł', form=form, legend='Nowy artykuł', categories=GetAllCategories())
def post_book(): form = PostForm() if form.validate_on_submit(): current_writer_name = form.book_writer.data.title() current_title_name = form.book_title.data.title() if BookWriter.query.filter_by( book_writer=current_writer_name).first() == None: current_writer = BookWriter( book_writer=form.book_writer.data.title()) db.session.add(current_writer) flash('New writer is added.') else: current_writer = BookWriter.query.filter_by( book_writer=current_writer_name).first() if BookTitle.query.filter_by( book_title=current_title_name).first() == None: current_title = BookTitle(book_title=form.book_title.data.title(), timestamp=datetime.utcnow(), author=g.user) db.session.add(current_title) flash('Your book is posted!') else: current_title = BookTitle.query.filter_by( book_title=current_title_name).first() flash('This book was posted earlier.') current_writer.add_composed(current_title) db.session.add(current_writer) db.session.commit() return redirect(url_for('index')) return render_template('post_book.html', form=form)
def index(page=1): posts = None form = PostForm() if form.validate_on_submit(): file_u = request.files['image'].read() image = Image.open(io.BytesIO(file_u)) scale = 1024 / image.size[0] image = image.resize((int(image.size[0] * scale), int(image.size[1] * scale)), Image.ANTIALIAS) img_byte_arr = io.BytesIO() image.save(img_byte_arr, format="PNG") file_u = img_byte_arr.getvalue() if request.files['image']: file_a = 'data:{};base64,{}'.format(request.files['image'].content_type, encode(file_u, 'base64').decode('utf-8')) post_create = Post.create(user=g.user.id, data=form.content.data, image=file_a) else: post_create = Post.create(user=g.user.id, data=form.content.data) for user in User.select(): user.sendmail_to(name=g.user.username, subject="TDIC Post", msg_text='{} posted: "{}".' .format(g.user.username, form.content.data), link=url_for("view_post", id=post_create.id) ) flash('Posted!') try: if current_user.is_authenticated: posts = Post.select().paginate(page, 21) except InternalError: DB.rollback() return render_template('index.html', posts=posts, page=page, options=True, form=form)
def new(): form = PostForm() if not current_user.can(Permission.WRITE_ARTICLES): abort(403) if form.validate_on_submit(): post = Post(body=form.body.data, title=form.title.data, viewed_count=0, author=current_user._get_current_object(), tags_txt=form.tags.data) db.session.add(post) tags = form.tags.data.split(';') for tag in tags: ttag = Tag.query.filter_by(content=tag).first() if ttag is not None: ttag.refer_count = ttag.refer_count + 1 else: ttag = Tag(content=tag, refer_count=1) post_tag = PostTag(post=post, tag=ttag) db.session.add(ttag) db.session.add(post_tag) flash(messages.post_create_ok) db.session.commit() return redirect(url_for('main.index', shows='home')) if None == form.body.data: form.body.data = '# 标题\n\n内容' if None == form.title.data: form.title.data = '输入博文名字' if None == form.tags.data: form.tags.data = '标签通过;隔开。' return render_template('edit.html', form=form)
def page(post_id=None): title = u'新增内容' form = PostForm() post = None # 读取操作 if request.method == 'GET' and post_id: title = u'修改内容' post = Post.query.get(post_id) form = PostForm(obj=post) # 新增、修改操作 elif request.method == 'POST' and form.validate_on_submit(): title = u'首页' # post = Post(user=g.user, topic=form.topic.data, title=form.title.data, body=form.body.data, sequence=form.sequence.data, timestamp=datetime.utcnow()) if form.id.data: # 修改 post = Post.query.get(form.id.data) form.populate_obj(post) else: # 新增 form.id.data = None post = Post(user=g.user, timestamp=datetime.utcnow()) form.populate_obj(post) db.session.add(post) db.session.commit() # .paginate(curpage, pagesize, <flag>) # flag:错误标记。如果是True,如果接收到超出记录范围的页面请求,那么404错误请求将会自动反馈到客户端浏览器。如果是False,那么一个空列表将会被返回,而不显示错误。 posts = Post.query.order_by(Post.sequence).filter_by(user=g.user).paginate(1, POSTS_PER_PAGE, False).items flash(u'保存成功') return redirect(url_for('index'))#render_template('index.html', title=title, posts=posts) return render_template('page.html', title=title, post=post, form=form)
def write(): if not current_user.is_administration(): abort(403) forms=PostForm() #查询到所有标签 categories=Category.query.order_by(Category.count.desc()) if forms.validate_on_submit(): #如果能查询到标签的话 tag = Category.query.filter_by(tag=forms.category.data).first() if tag is not None: post=Post(title=forms.title.data,body=forms.body.data, summary=forms.summary.data,category=tag) tag.count+=1 db.session.add(post) db.session.commit() else: category=Category(tag=forms.category.data,count=1) post=Post(title=forms.title.data,body=forms.body.data, summary=forms.summary.data,category=category) db.session.add(post) db.session.commit() flash('You have written an article') return redirect(url_for('main.index')) return render_template('write.html',form=forms,categories=categories)
def index(page = 1): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, timestamp = datetime.utcnow(), author = g.user) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('index')) user = g.user ''' posts = [ # fake array of posts { 'author': {'nickname': 'John'}, 'body': 'Beautiful day in Portland!' }, { 'author': { 'nickname': 'Susan' }, 'body': 'The Avengers movie was so cool!' } ] ''' #posts = g.user.followed_posts().all() # retrieve all items posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False) # start with page 1, retrieve 3 elements, False (when an error occurs, an empty list will be retrieved) flash('posts: ' + str(len(posts.items))) flash(user.nickname) return render_template('index.html', title ='Home', user = user, form = form, posts = posts)
def wall(wid): form = PostForm() error = None pic = '' #print '***************************************' if form.validate_on_submit(): content = form.content.data posted = datetime.utcnow() if request.method == 'POST': file = request.files['file'] #print 'request' if file and allowed_file(file.filename): pic = secure_filename(file.filename) file.save(os.path.join(IMAGE_SRC, pic)) #print 'filename:'+pic post = Post(writer=g.user.uid, wid=wid, content=form.content.data, pic=pic, posted=posted) db.session.add(post) db.session.commit() #print 'redirect @@@@@@@@@@@@@@@@@@@@@@@' #print 'REDIRECT[1]: wall_id'+wid return redirect(url_for('wall',wid=wid)) else: post = Post(writer=g.user.uid, wid=wid, content=form.content.data, pic='', posted=posted) db.session.add(post) db.session.commit() #print 'REDIRECT[2]: wall_id'+wid return redirect(url_for('wall',wid=wid)) belongs = User.query.filter_by(uid=wid).first() wall = db.session.query(User,Post).filter(Post.wid==wid).filter(User.uid==Post.writer).order_by(Post.pid.desc()).all() #print wall #print 'render: wid'+wid+' ^^^^^^^^^^^^^^^^^^^^^' return render_template("wall.html", form=form, wall=wall, belongs=belongs, writer=g.user)
def index(): form = PostForm() if current_user.can( Permissions.WRITE_ARTICLES) and form.validate_on_submit(): post = Post(body=form.body.data, author=current_user._get_current_object()) db.session.add(post) return redirect(url_for('.index')) page = request.args.get('page', 1, type=int) show_followed = False if current_user.is_authenticated: show_followed = bool(request.cookies.get('show_followed', '')) if show_followed: query = current_user.followed_posts else: query = Post.query pagination = query.order_by(Post.timestamp.desc()).paginate( page, per_page=current_app.config['FLASK_BLOG_POSTS_PER_PAGE'], error_out=False) posts = pagination.items return render_template('index.html', form=form, posts=posts, show_followed=show_followed, pagination=pagination)
def group(group_name, page=1): gr = Group.query.filter(Group.name==group_name).first() if not gr: flash("'"+group_name+"' does not exist!", 'error') return redirect(url_for('home')) postForm = PostForm() postForm.postType.choices = [(GENERAL_POST, "Post"), (PRAYER_POST, "Prayer")] if postForm.validate_on_submit(): post = Post(body = postForm.post.data, timestamp = datetime.utcnow(), author = g.user, group=gr, postType=postForm.postType.data) db.session.add(post) db.session.commit() if postForm.postType.data == PRAYER_POST: flash('Your prayer post is now live!', 'info') else: flash('Your post is now live!', 'info') return redirect(url_for('group', group_name=group_name)) postForm.postType.data = GENERAL_POST posts = Post.query.filter(Post.group_id == gr.id).order_by(Post.timestamp.desc()).paginate(page, POSTS_PER_PAGE, False) return render_template('group.html', group=gr, posts=posts, form=postForm, page="group")
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.theme.data: theme_file = save_theme(form.theme.data) post.theme = theme_file else: theme_file = url_for('static', filename='post_pics/blog_default') db.session.commit() flash("Your post has been updated!", 'success') return redirect(url_for('post', post_id=post.id)) elif request.method == 'GET': form.title.data = post.title form.content.data = post.content form.theme.data = post.theme return render_template('create_post.html', title='Update Post', content=form.content.data, form=form, legend='Update Post')
def index(page=1): """Index function @login_required decorator requires user to be logged in before they can view this URL. Flask-Login will redirect user to login function if not already logged in (configured in __init__.py). """ form = PostForm() # If post blog form is filled out, insert new post record in DB if form.validate_on_submit(): post = Post( body=form.post.data, timestamp=datetime.utcnow(), author=g.user) db.session.add(post) db.session.commit() flash('Your post is now live!') # 'url_for' is a clean way for Flask to obtain the URL of a # given view function. # Redirect here to refresh page to show new post return redirect(url_for('index')) # Get posts from followed users from the DB. # Pagination takes 3 args: page number, posts per page (config) # and an error flag (if true out of range error posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False) # render_template function takes the template name and template # arguments, and returns the rendered template with placeholders # replaced (using Jinja2 templating, as part of Flask). return render_template( 'index.html', title='Home', form=form, posts=posts)
def posts_add(group_id): """Add a post to a group: Show form if GET. If valid, update message and redirect to user page. """ if not g.user: flash("Access unauthorized.", "danger") return redirect("/") form = PostForm() if form.validate_on_submit(): group = Group.query.get(group_id) groupid = group.id post = Post(title=form.title.data, text=form.text.data, group_id=groupid) #db.session.add(post) g.user.post.append(post) #db.session.add(group) #group.post.append(post) #group.post.append(post) #g.user.groups.append(post) #group.post.append(group) #post.group.append(group) #db.session.add(group) #db.session.add(post) db.session.commit() return redirect(f"/group/{group.id}") return render_template('newpost.html', form=form)
def index(page=1): # user = {'nickname':'Miguel'} from forms import PostForm from models import Post user = g.user form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, timestamp=datetime.utcnow(), author=g.user) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('index')) # posts = [ # { # 'author': {'nickname': 'john'}, # 'body': 'Beautiful day in Portland!' # }, # { # 'author': {'nickname': 'Susan'}, # 'body': 'The Avengers movie was so cool!' # } # ] # posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False).items posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False) return render_template('index.html', title='Home', form=form, user=user, posts=posts)
def index(page=1): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, timestamp=datetime.utcnow(), author=g.user) db.session.add(post) db.session.commit() flash('Your post is now live.') return redirect(url_for('index')) user = g.user posts = g.user.followed_posts().paginate(page, app.config['POSTS_PER_PAGE'], False) #.items#all() # posts = [ # { # 'author':{'nickname':'John'}, # 'body':'Beautiful day in Portland!' # }, # { # 'author': { 'nickname': 'Susan' }, # 'body': 'The Avengers movie was so cool!' # } # ] return render_template('index.html', title='Home', form=form, posts=posts)
def index(page = 1): form = PostForm() if form.validate_on_submit(): language = guessLanguage(form.post.data) if language == 'UNKNOWN' or len(lanaguage) >5: language = '' post = Post(body = form.post.data, timestamp = datetime.utcnow(), author = g.user, language = language) db.session.add(post) db.session.commit() flash(gettext('Your post is now live!')) return redirect(url_for('index')) posts = g.user.followed_posts().paginate(page, POST_PER_PAGE, False) return render_template("index.html", title = "Home", form = form, posts = posts)
def post(): form = PostForm() if form.validate_on_submit(): flask.app.posts.append(Post(form.title.data, flask.app.user.username, form.body.data)) flash('Post Created', 'success') return make_response(redirect(url_for('main'))) return render_template('post.html', title = "Post", form = form, loggedin = flask.app.loggedin)
def edit(id=0): form = PostForm() if id == 0: post = Post() else: post = Post.query.get_or_404(id) if form.validate_on_submit(): post.title = form.title.data post.body = form.body.data post.author = current_user._get_current_object() db.session.add(post) try: db.session.commit() except: db.session.rollback() time.sleep(1) return redirect(url_for('main.posts', id=post.id)) # 在这里用redirect,不能用render_template form.title.data = post.title form.body.data = post.body title = _(u'添加新文章') if id > 0: title = _(u'编辑文章') + '-' + _(post.title) return render_template('posts/edit.html', post=post, form=form, title=title)
def upload(): form = PostForm() # Get the name of the uploaded file file = request.files['file'] # Check if the file is one of the allowed types/extensions if file and allowed_file(file.filename): # Make the filename safe, remove unsupported chars filename = secure_filename(file.filename) # Move the file form the temporal folder to # the upload folder we setup file.save(os.path.join(app.config['UPLOAD_FOLDER']+current_user.user_name, filename)) # Redirect the user to the uploaded_file route, which # will basicaly show on the browser the uploaded file if form.validate_on_submit(): post = Post(body = form.body.data, user_name= current_user.user_name, author=current_user._get_current_object(), url = app.config['UPLOAD_FOLDER'] + current_user.user_name + '/'+ filename, location = form.location.data) db.session.add(post) db.session.commit() return redirect(url_for('.index')) return redirect(url_for('uploaded_file', filename=filename))
def add_post(user_id): form = PostForm() if request.method == "POST": if form.validate_on_submit(): userid = user_id caption = request.form['caption'] photo = request.files['postimage'] post_date = datetime.datetime.now() post_photo = secure_filename(photo.filename) post = Posts(user_id = userid, postimage = post_photo, caption = caption, created_on = post_date) db.session.add(post) db.session.commit() photo.save(os.path.join(filefolder, post_photo)) return jsonify({'message':"Successfully created a new post"}) elif request.method == "GET": user = Users.query.filter_by(id = user_id).first() if not user: return jsonify({'message': "no user found"}) user_posts = Posts.query.filter_by(user_id = user_id).all() userposts = [] for user_post in user_posts: post_data = {'id':user_post.id,'user_id': user_post.user_id,'postimage': user_post.post_photo,'caption': user_post.caption,'created_on': user_post.post_date} userposts.append(post_data) return jsonify(data = userposts) error_msgs = form_errors(form) error = [{'errors': error_msgs}] return jsonify(errors = error)
def new_post(): form = PostForm() mytext = form.content.data title = form.title.data if form.validate_on_submit(): if form.generate.data: text = aiLive.generatePeriod(mytext) form.poetry.data = text return render_template('create_post.html', title='New Post', form=form) if form.submit.data: if form.poetry.data != "": post = Post(title=form.title.data, content=form.content.data, author=current_user, generated=form.poetry.data) db.session.add(post) db.session.commit() flash('Your post have been created', 'success') return redirect(url_for('generator.index')) else: flash('Please generate something first', 'error') return render_template('create_post.html', title='New Post', form=form)
def index(): if current_user.is_anonymous: return redirect(url_for('login')) 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 return render_template('index.html' , current_user=current_user , posts=posts.items , form=form , next_url=next_url , prev_url=prev_url )
def user(): user_id = request.args.get("user_id") if user_id == None: user_id = current_user.id # enable registration link current_cycle = model.session.query(model.SeasonCycle).\ order_by(model.SeasonCycle.id.desc()).\ first() #print current_cycle.cyclename users= model.session.query(model.User) user = users.get(user_id) form= PostForm() if form.validate_on_submit(): new_post = model.session.\ add(model.Post(body=form.post.data, user_id= g.user.id)) model.session.commit() flash('Your post is live!') return redirect('user') return render_template('user.html', title= 'Profile', users=users, user = user, current_cycle=current_cycle, form=form)
def new_post(): if 'username' not in session: return redirect(url_for('login')) form = PostForm() if form.validate_on_submit(): encoded_string = resize_encode_img(form.content.data) picture_details = dict() picture_details['username'] = session['username'] picture_details['title'] = form.title.data picture_details['image_base64'] = encoded_string.decode() status = requests.post( 'https://mnu7f7vb6l.execute-api.ap-southeast-1.amazonaws.com/ISS/postpicture', json=picture_details, headers={ 'content-type': 'application/json', 'authorization': session['token'] }) if status.status_code != 200 or (status.json().get('statusCode') != 200) or (status.json().get('message') == 'Unauthorized'): flash('Something went wrong, please try again', 'danger') else: flash('Your picture has been posted!', 'success') time.sleep(5) return redirect(url_for('home')) return render_template('create_post.html', title='New Post', form=form, legend='New Post')
def new_post(): form = PostForm() if form.validate_on_submit(): flash('Your Post has been Posted!', 'success') db.add_post(current_user.user_id, form.title.data, form.content.data) return redirect(url_for('home')) return render_template('create_post.html', title='New Post', form=form)
def user(): user_id = request.args.get("user_id") if user_id == None: user_id = current_user.id # enable registration link current_cycle = model.session.query(model.SeasonCycle).\ order_by(model.SeasonCycle.id.desc()).\ first() #print current_cycle.cyclename users = model.session.query(model.User) user = users.get(user_id) form = PostForm() if form.validate_on_submit(): new_post = model.session.\ add(model.Post(body=form.post.data, user_id= g.user.id)) model.session.commit() flash('Your post is live!') return redirect('user') return render_template('user.html', title='Profile', users=users, user=user, current_cycle=current_cycle, form=form)
def nowy_post(): form = PostForm() if form.validate_on_submit(): cleaned_data = bleach.clean( form.body.data, tags=bleach.sanitizer.ALLOWED_TAGS + [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'iframe', 'img', 'p', 'pre', 'src', 'u', 'sup', 'sub', 'strike', 'br' ], attributes=bleach.sanitizer.ALLOWED_ATTRIBUTES) post = Entry( title=form.title.data, body=cleaned_data, published=form.status.data, ) db.session.add(post) db.session.commit() slug = slugify(str(post.id) + '-' + post.title) post.slug = slug db.session.commit() flash('Post został dodany', 'success') return redirect(url_for('article', slug=slug)) return render_template('create.html', form=form)
def post(self): form = PostForm() if request.method == 'POST': if form.validate_on_submit(): post = Post.create() form.populate_obj(post) f = request.files.get('file') post.user = current_user if f: picture = Picture.create() picture.save_file(f, current_user) post.cover_picture_id = picture.id if picture else 0 post.update_score(page_view=1) post.save() if form.remain.data: url = url_for('PostsView:put', id=post.id) else: url = url_for('PostsView:get', id=post.id) return resp(url, redirect=True, message=gettext('Stamp succesfully created')) else: return resp('admin/posts/edit.html', status=False, form=form, message=gettext('Invalid submission, please check the message below')) return resp('admin/posts/edit.html', form=form)
def edit_post(id): form = PostForm() if users.is_current_user_admin() and form.validate_on_submit(): try: tags = Tags() categories = Categories() updating_post = BlogPost.get(int(id)) title = request.json['title'] body = request.json['body'] raw_category = request.json['category'] editing_tags = request.json['tags'] raw_summary = request.json['summary'] tags_keys = tags.update(editing_tags, updating_post) category_key = categories.update(raw_category, updating_post.category) updating_post.edit(title, body, datetime.now(), tags_keys, category_key, raw_summary, raw_answers=request.json['answers']) except AttributeError: abort(500) return jsonify(updating_post.to_json()) # dangerous
def new_post(): pather = "" form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) post.title = form.title.data post.content = form.content.data if form.theme.data: theme_file = save_theme(form.theme.data) post.theme = theme_file else: theme_file = url_for('static', filename='post_pics/blog_default') p1 = Post.query.filter_by(title=form.title.data).first() if p1: Post.theme = theme_file db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') return redirect(url_for('home')) elif request.method == 'GET': theme_file = url_for('static', filename='post_pics/blog_default') theme_file = url_for('static', filename='post_pics/blog_default') return render_template('create_post.html', title='New Post', content=form.content.data, form=form, legend='Create Post')
def user(nickname, page=1): user = User.query.filter_by(nickname = nickname).first() if user == None: flash('User ' + nickname + ' not found.', 'error') return redirect(url_for('home')) form = PostForm() form.postType.choices = [(GENERAL_POST, "Post"), (PRAYER_POST, "Prayer")] if form.validate_on_submit(): post = Post(body = form.post.data, timestamp = datetime.utcnow(), author = g.user, postType=form.postType.data) db.session.add(post) db.session.commit() if form.postType.data == PRAYER_POST: flash('Your prayer post is now live!', 'info') else: flash('Your post is now live!', 'info') return redirect(url_for('user', nickname=nickname)) form.postType.data = GENERAL_POST posts = user.posts.order_by(Post.timestamp.desc()).paginate(page, POSTS_PER_PAGE, False) prayerListPosts = user.get_prayers().limit(POSTS_PER_PAGE) return render_template('user.html', user = user, form=form, posts = posts, prayerListPosts = prayerListPosts, page='user')
def comment(id): form = PostForm() if form.validate_on_submit(): if request.files['content']: if 'image' in request.files['content'].content_type: file_u = request.files['content'].read() if getsizeof(file_u) <= 3000000: file_a = 'data:{};base64,{}'.format( request.files['content'].content_type, encode(file_u, 'base64').decode('utf-8')) post_create = Post.create(user=g.user.id, data=file_a) flash('Posted!') return redirect(url_for('index')) else: flash('Image is bigger than 3 mb.') else: file_u = request.files['content'].read() if getsizeof(file_u) <= 3000000: file_a = 'data:{};base64,{}'.format( request.files['content'].content_type, encode(file_u, 'base64').decode('utf-8')) post_create = Post.create(user=g.user.id, data=file_a) flash('Posted!') return redirect(url_for('index')) else: flash('Image is bigger than 3 mb.') return redirect(url_for('index'))
def index(page = 1): # user = {'nickname': 'Ang'} # fake user form = PostForm() if form.validate_on_submit(): language = guessLanguage(form.post.data) if language == 'UNKNOWN' or len(language) > 5: language = '' post = Post(body = form.post.data, timestamp = datetime.utcnow(), author= g.user, language = language) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('index')) # posts = g.user.followed_posts().all() posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False) # posts = [ # fake array of posts # { # 'author' : {'nickname' : 'Ang'}, # 'body' : 'Beautiful day in Ireland!' # }, # { # 'author' : {'nickname' : 'Gao'}, # 'body' : 'Hacking a blog' # } # ] return render_template('index.html', title = 'Home', form = form, posts=posts)
def update_post(post_id): post = Post.query.get_or_404(post_id) if post.email != current_user.get_id(): abort(403) form = PostForm() if form.validate_on_submit(): post.item_name = form.item_name.data post.file_path = form.file_path.data post.is_public = form.is_public.data item_id = post.id update_share = form.shared_group.data if not update_share: share_to = share(owner_email=current_user.get_id(), item_id=item_id, fg_name=form.shared_group.data) db.session.add(share_to) db.session.commit() elif request.method == 'GET': form.item_name.data = post.item_name form.file_path.data = post.file_path form.is_public.data = post.is_public return render_template('create_post.html', title='Update Post', form=form, legend='Update Post')
def new_post(): fgs_own = FriendGroup.query.filter_by(id=current_user.get_id()).all() belongs = belong.query.filter_by(email=current_user.get_id()).all() form = PostForm() if form.validate_on_submit(): post = Post(email=current_user.get_id(), file_path=form.file_path.data, item_name=form.item_name.data, is_public=form.is_public.data) db.session.add(post) db.session.commit() item_id = post.id if not form.shared_group.data: share_to = share(owner_email=current_user.get_id(), item_id=item_id, fg_name=form.shared_group.data) db.session.add(share_to) db.seession.commit() flash('Your post has been created!', 'Success') return redirect(url_for('home')) return render_template('create_post.html', title='New Post', form=form, legend='New Post', fgs_own=fgs_own, belongs=belongs)
def post(): form = PostForm() if form.validate_on_submit(): redis_store.set('posts', {'title':form.title.data,'text':form.text.data}) return redirect(url_for('index')) return render_template('form.html', title = 'Create Post', form = form)
def write(): form = PostForm() if form.validate_on_submit(): post = Post(body = form.body.data) db.session.add(post) flash('You have successed publishing a blog! Forgive my poor English!') return redirect(url_for('.index')) return render_template('write.html', form = form)
def post(): form = PostForm() if form.validate_on_submit(): post = Algorithm(name=form.name.data, language=form.language.data, timestamp=datetime.utcnow(), body=form.body.data) db.session.add(post) db.session.commit() return redirect('algos/id/' + str(post.id)) return render_template('info/post.html', title = HEADER + 'Post', form=form)
def index(): form = PostForm() if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit(): post = Post(body = form.body.data, author = current_user._get_current_object()) db.session.add(post) return redirect(url_for('index')) posts = Post.query.order_by(Post.timestamp.desc()).all() return render_template('index.html', form = form, posts = posts)
def create_post(): """Método responsável em salvar informações do blog.""" form = PostForm() if form.validate_on_submit(): form.save() flash('Post foi salvo no banco de dados.') return redirect(url_for('get')) return render_template('form_post.html', form=form, title='Criar post', action="create")
def create_post(): form = PostForm(request.form) if form.validate_on_submit(): post = Post(title=form.title.data, body = form.body.data, author = flask_login.current_user) db.session.add(post) db.session.commit() return redirect(url_for('posts')) return render_template("create_post.html", form = form)
def blog(): user = g.user form = PostForm() if form.validate_on_submit(): post = models.Post(body=form.body.data, user_id=user.id, user_nickname=user.nickname) db.session.add(post) db.session.commit() return redirect(url_for('index')) return render_template('blog.html', title='Create New Blog', user=user, form=form)
def profile(): form=PostForm(request.form) if form.validate_on_submit(): post=Post(post=form.post.data, user_id=g.user) db.session.add(post) db.session.commit() return redirect(url_for('profile')) posts = g.user.followed_posts() return render_template("profile.html", user=g.user, posts=posts)
def post(): form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, body = form.body.data, author = current_user._get_current_object()) db.session.add(post) return redirect(url_for('main.index')) return render_template('admin/post.html',form=form)
def add_post_post(): form = PostForm() if form.validate_on_submit(): post = models.Post( text=form.text.data, timestamp=datetime.datetime.utcnow(), user_id=current_user.id) db.session.add(post) db.session.commit() return redirect(url_for('posts.posts')) return render_template('add_post.html', title='Add Post', users=models.User.query.all(), form=form), 400
def show_entries(page=1): form = PostForm() if form.validate_on_submit(): post = Post(body = form.post.data, timestamp = datetime.utcnow(), author = g.user) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('show_entries')) return render_template('show_entries.html', posts=Post.query.order_by(Post.timestamp.desc()).paginate(page,POSTS_PER_PAGE, False), user=current_user, form=form)
def index(page=1): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, timestamp=datetime.utcnow(), author=g.user) db.session.add(post) db.session.commit() flash(choice(app.config['MSG']['confirm_post'])) return redirect(url_for('index')) posts = g.user.followed_posts().paginate(page, app.config['POSTS_PER_PAGE'], False) return render_template('index.html', title='Home', user=g.user, form=form, posts=posts, max_post_length=app.config['MAX_POST_LENGTH'], inspiration=choice(app.config['MSG']['inspiration']))
def edit(id): post = Post.query.get_or_404(id) form = PostForm() if form.validate_on_submit(): post.body = form.body.data db.session.add(post) flash('The post has been updated.') return redirect(url_for('.post', id=post.id)) form.body.data = post.body return render_template('edit_post.html', form=form)