def post_edit(request, track_id=None, point_id=None): if track_id is not None: track = get_object_or_404(Track, id=track_id) url_name = 'manager_tracks' elif point_id is not None: track = get_object_or_404(Point, id=point_id) url_name = 'manager_points' else: return HttpResponseNotFound() if track.post is None: post = Post(title=track.name, text='') post.save() track.post = post track.save() else: post = track.post if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() if request.POST.get('submit', 'to_current_page') == 'to_section': return HttpResponseRedirect(reverse(url_name)) else: form = PostForm(instance=post) title = u'Редактирование "%s"' % post.title return render_to_response('post_edit.html', {'form': form, 'title': title, 'back_url': reverse(url_name) }, RequestContext(request))
def new_message(request, mlist_fqdn): """ Sends a new thread-starting message to the list. TODO: unit tests """ store = get_store(request) mlist = store.get_list(mlist_fqdn) failure = None if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): today = datetime.date.today() redirect_url = reverse('archives_with_month', kwargs={ "mlist_fqdn": mlist_fqdn, 'year': today.year, 'month': today.month }) redirect_url += "?msg=sent-ok" try: post_to_list(request, mlist, form.cleaned_data['subject'], form.cleaned_data["message"], attachments=request.FILES.getlist("attachment")) except PostingFailed, e: failure = str(e) else: return redirect(redirect_url)
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 submit_post(request, board_id): if not request.user.is_authenticated or request.user.username == "": return render(request, 'login.html', {}) try: board = DefaultBoard.objects.get(pk=board_id) if not board.access(request.user, access_type="post", default=False): return render(request, 'board_noperm.html', {}) if request.method == "POST": # Actual submission form = PostForm(request.POST) if not form.is_valid(): return Http404("Error submitting post.") text = form.cleaned_data['text'] new_post = board.create_post(subject=form.cleaned_data['subject'], text=text, author_name=request.user.username, author_player=request.user) return HttpResponseRedirect("/boards/" + str(board.id) + "/" + str(new_post.id) + "/") else: form = PostForm() context = {'board': board, 'board_id': board.id, 'form': form} return render(request, 'submit_post.html', context) except (Board.DoesNotExist, Board.MultipleObjectsReturned): return Http404("Error accessing boards.")
def new_thread(request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) if request.method == "POST": thread_form = ThreadForm(request.POST) post_form = PostForm(request.POST) if thread_form.is_valid() and post_form.is_valid(): thread = thread_form.save(False) thread.subject = subject thread.user = request.user thread.save() post = post_form.save(False) post.user = request.user post.thread = thread post.save() messages.success(request, "You have create a new thread!") return redirect(reverse('thread', args={thread.pk})) else: thread_form = ThreadForm() post_form = PostForm(request.POST) args = { 'thread_form': thread_form, 'post_form': post_form, 'subject': subject, } args.update(csrf(request)) return render(request, 'forum/thread_form.html', args)
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 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 post(self, request, grpid): ''' make a post for given group and render ''' try: post_author = request.user.membership_set.get(group__pk=grpid) except: return HttpResponseForbidden() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) # author = from the current user's set of memberships, the one that # has a group with matching group id (pk) post.author = post_author post.save() # is anybody listening? # if so, send new post to everyone and reset grpid = int(grpid) # Send notifications. uid = request.user.id self._send_notifications( uid, grpid, PostNotification, post) if grpid in self.group_event: self.group_event[grpid].set(post) # self.group_event = None del self.group_event[grpid] return render(request, 'group_post.html', {'post': post}) return HttpResponseBadRequest()
def addpost(request): if request.POST: #files = upload_receive(request) form = PostForm(request.POST, request.FILES) if form.is_valid(): f2 = form.save(commit=False) f2.pub_date = datetime.now() f2.save() tags = f2.tags tags = tags.split(',') tagobjs = Tag.objects.all() taglist=[] for i in tagobjs: #Adding new tags taglist.append(i.name) for i in tags: if i not in taglist: obj = Tag(name=i) obj.save() print 'saved' print obj print obj.name taglist.append(i) return HttpResponseRedirect('/blog/viewposts/') else: args = {} args.update(csrf(request)) args['form']=form args['error']='Some error in form' return render_to_response('addpost.html',args) else: args = {} args.update(csrf(request)) args['form'] = PostForm() return render_to_response('addpost.html',args)
def create_post(request): # Get the context from the request. context = RequestContext(request) # A HTTP POST? if request.method == 'POST': form = PostForm(request.POST) # Have we been provided with a valid form? if form.is_valid(): # Save the new category to the database. form.save(commit=True) # Now call the index() view. # The user will be shown the homepage. return HttpResponseRedirect('/') else: # The supplied form contained errors - just print them to the terminal. print form.errors else: # If the request was not a POST, display the form to enter details. form = PostForm() # Bad form (or form details), no form supplied... # Render the form with error messages (if any). return render_to_response('posts/create_post.html', {'form': form}, context)
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 post(request): """process post page judge user's authenticate status and save valid post""" if request.user.is_authenticated(): form = PostForm() if request.method == "POST": form = PostForm(request.POST.copy()) if form.valid(): poster = request.user title = form.cleaned_data["title"] content = form.cleaned_data["content"] bonus = form.cleaned_data["bonus"] post = Ability( abilityNAME=title, abilityDESCRIBE=content, logDATE=datetime.datetime.now(), rpREQUIRED=bonus, abilityRAISER=poster, ) post.save() return HttpResponseRedirect("/") form = PostForm() return render_to_response("sells/post.html", {"form": form}) return HttpResponseRedirect("/accounts/login/")
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 post(self, board, thread): logging.info("post called") ip = self.request.remote_addr qkey = "ip-%s" % ip quota = memcache.get(qkey) or 0 quota += 1 memcache.set(qkey, quota, time=POST_INERVAL*quota) logging.info("ip: %s, quota: %d" % (ip, quota)) if quota >= POST_QUOTA: return redirect("http://winry.on.nimp.org" ) # validate post form form = PostForm(self.request.form) if not form.validate(): return redirect("/%s/" % board) # if ok, save logging.info("data valid %r" %( form.data,)) post, thread = save_post(self.request, form.data, board, thread) key = board + "%d" % post cookie = self.get_secure_cookie(key) cookie["win"] = key return redirect("/%s/%d" % (board, thread))
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 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 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(): 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 new_message(request, mlist_fqdn): """ Sends a new thread-starting message to the list. TODO: unit tests """ store = get_store(request) mlist = store.get_list(mlist_fqdn) failure = None if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): today = datetime.date.today() redirect_url = reverse( 'archives_with_month', kwargs={ "mlist_fqdn": mlist_fqdn, 'year': today.year, 'month': today.month}) redirect_url += "?msg=sent-ok" try: post_to_list(request, mlist, form.cleaned_data['subject'], form.cleaned_data["message"], attachments=request.FILES.getlist("attachment")) except PostingFailed, e: failure = str(e) else: return redirect(redirect_url)
def new_post(request): """ New_post function that returns the new post view returns a rendered view and recieves a request """ # Validate the request is a post method and not a get if request.method == "POST": # initialize the post form with what the post sends post_form = PostForm(request.POST, prefix="post_form") instance = post_form.save(commit=False) instance.save() # for for reading all the files for count, x in enumerate(request.FILES.getlist("files")): # call the funciton porcess_file save_image(x, instance.id) # initialize a context object context = {"title": "add a new post", "post_form": post_form} # reutrn the view again but with the post form validated return render(request, "admin_uploads/new_post.html", context) # If it is a get pettition else: # initialize the post form with nothing post_form = PostForm(prefix="post_form") # initialize a context object context = {"title": "add a new post", "post_form": post_form} # return a rendered view with the form that has nothing return render(request, "admin_uploads/new_post.html", context)
def index(): from models import Post, User from forms import PostForm if request.method == 'POST': print(request.form) form = PostForm(request.form) if form.validate(): post = Post(**form.data) db.session.add(post) db.session.commit() flash('Post created!') else: flash('Form is not valid! Post was not created.') flash(str(form.errors)) posts = Post.query.all() for post in posts: user_id = post.user_id user = User.query.filter_by(id=user_id).first() print(post.user_id, user) print(post.user) return render_template('home.txt', posts=posts)
def post_new(request): """新建文章""" if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user # 开始处理标签 print post.author ptags = request.POST['tags'].strip() all_tags = [] if ptags: tags = ptags.split(',') for tag in tags: try: t = Tag.objects.get(name=tag) except Tag.DoesNotExist: t = Tag(name=tag) t.save() all_tags.append(t) post.save() for tg in all_tags: post.tags.add(tg) return redirect('blog.views.post_detail', pk=post.pk) else: form = PostForm() return render_to_response('post_edit.html', {'form': form, 'is_new': True},context_instance=RequestContext(request))
def post_view(request): user = check_validation(request) if user: if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image, caption=caption) post.save() path = str(BASE_DIR + post.image.url) client = ImgurClient( '9c9bf0c17f4ac16', 'cd2f3f14d28677368f0c26ee558ff6841e6e098a') post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() return redirect('/feed/') else: form = PostForm() return render(request, 'post.html', {'form': form}) else: return redirect('/login/')
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 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 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 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 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 sub_post(request, id_num): #for nested posts pform = PostForm(request.POST or None) parent = get_object_or_404(Post, pk=id_num) if (request.method == 'POST' and request.user.is_authenticated()): if pform.is_valid(): title = pform.cleaned_data["title"] check = Post.objects.filter(title=title).order_by("-identifier") check_int = 0 if len(check) > 0: check_int = check[0].identifier + 1 post = Post(title=title, body=pform.cleaned_data["body"], parent=parent, user=request.user, identifier=check_int) post.save() messages.success(request, "Post submitted correctly") else: ### meaningful errors here would be helpful ### messages.error(request, pform.errors) return render_to_response("post_form.html", {'pform' : pform, 'post':parent}, RequestContext(request)) return HttpResponseRedirect("/posts/"+id_num)
def post_view(request): user = check_validation(request) if user: if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image, caption=caption) post.save() path = str(BASE_DIR + '//' + post.image.url) client = ImgurClient( '4bede6ccfad6060', 'c598dc22ffa6f6521d905311f2fab28b89098885') post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() app = ClarifaiApp(api_key="c106317b6810482599634b443a8e01d8") model = app.models.get('general-v1.3') response = model.predict_by_url(url=post.image_url) print response return redirect('/feed/') else: form = PostForm() return render(request, 'post.html', {'form': form}) else: return redirect('/login/')
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 post_view(request): user = check_validation(request) if user: if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') #caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image) post.save() path = str(BASE_DIR + post.image.url) client = ImgurClient(YOUR_CLIENT_ID, YOUR_CLIENT_SECRET) post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() ctypes.windll.user32.MessageBoxW( 0, u"post successsfully created", u"SUCCESS", 0) return redirect('/feed/') else: form = PostForm() return render(request, 'post.html', {'form': form}) else: return redirect('/login/')
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 post_view(request): user = check_validation(request) if user == None: return redirect('/login/') elif request.method == 'GET': post_form = PostForm() return render(request, 'post.html', {'post_form': post_form}) elif request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image, caption=caption) post.save() client = ImgurClient( '13aab932636aa80', '5d78c0178cb9258255982d328f803d536413f567') path = str(BASE_DIR + "\\" + post.image.url) post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() return redirect("/feed/") else: return HttpResponse("Form data is not valid.") else: return HttpResponse("Invalid request.")
def post_view(request): user = check_validation(request) if user: if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image, caption=caption) post.save() path = str(BASE_DIR + '/' +post.image.url) client = ImgurClient(YOUR_CLIENT_ID, YOUR_CLIENT_SECRET) post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() return redirect('/feed/') else: form = PostForm() return render(request, 'post.html', {'form': form}) else: return redirect('/login/')
def new_message(request, mlist_fqdn): """ Sends a new thread-starting message to the list. TODO: unit tests """ store = get_store(request) mlist = store.get_list(mlist_fqdn) if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): _send_email(request, mlist, form.cleaned_data['subject'], form.cleaned_data["message"]) today = datetime.date.today() redirect_url = reverse( 'archives_with_month', kwargs={ "mlist_fqdn": mlist_fqdn, 'year': today.year, 'month': today.month}) redirect_url += "?msg=sent-ok" return redirect(redirect_url) else: form = PostForm() context = { "mlist": mlist, "post_form": form, 'months_list': get_months(store, mlist.name), } return render(request, "message_new.html", context)
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 editpost(request, post_id): args = {} args.update(csrf(request)) #info gathering-------------------------------------------------------- m = get_object_or_404(Member, user=request.user.profile) p = Post.objects.get(id=post_id) #making some fun stuff----------------------------------------------- if m == p.user: if request.method == 'POST': form = PostForm(request.POST, request.FILES, instance=p) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('post', kwargs={"post_id": post_id})) else: form = PostForm(instance=p) else: raise Http404 #packing bags and fly-------------------------------------------------- args.update({'form': form}) template = 'editpost.html' context = RequestContext(request) return render_to_response(template, args, context_instance=context)
def add_post(request, thread_slug, post_id=None, template="forum/add_post.html"): "Add new post" t = get_object_or_404(Thread, slug=thread_slug) u = request.user if t.closed: return HttpResponseRedirect(t.get_absolute_url()) if t.latest_post.author == u: return edit_post(request, thread_slug, t.latest_post.id) #return HttpResponseRedirect(t.get_absolute_url()) if request.POST: p = Post(thread=t, author=u) f = PostForm(request.POST, instance=p) if f.is_valid(): f.save() return HttpResponseRedirect(t.get_absolute_url()) else: data = {} if post_id: q_post = t.post_set.get(id=post_id) q_info = u">**%s powiedział:**\n>" % q_post.author.username q_info = [q_info, ] q_msg = [l for l in q_post.text.split("\n")] data['text'] = "\n> ".join(q_info + q_msg) + "\n\n" f = PostForm(data) return render_to_response(template, { "topic": t, "form": f, }, context_instance=RequestContext(request))
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 add_thread(request, template="forum/add_thread.html"): "Create new thread and first post" def get_slug(text, numb=0): "Create unique slug" text = text[:110] if numb: text = text.rsplit("_", 1)[0] + "_%d" % numb s = slugify(text) if Thread.objects.filter(slug=s).count(): return get_slug(text, numb + 1) return s u = request.user tf = ThreadForm() pf = PostForm() if request.POST: t = Thread(author=u, latest_post_author=u, slug=get_slug(request.POST['title'])) tf = ThreadForm(request.POST, instance=t) if tf.is_valid(): tfins = tf.save() p = Post(thread=tfins, author=u) pf = PostForm(request.POST, instance=p) if pf.is_valid(): pfins = pf.save() return HttpResponseRedirect(tfins.get_absolute_url()) else: tfins.delete() return render_to_response(template, { "t_form": tf, "p_form": pf, }, context_instance=RequestContext(request))
def post(request): if request.method == 'POST': post_form = PostForm(request.POST) username = str(request.user) if post_form.is_valid(): title = post_form.cleaned_data.get('title','') body = post_form.cleaned_data.get('body','') new_post = { 'title':title, 'body':body, 'author':username, 'time':time.time(), 'show':True, 'type':'post', 'comments':[], } post_id = make_post(new_post) user_post(username,post_id) else: print "form was not valid" return HttpResponseRedirect(reverse('forum:home'))
async def _post(request, post_id=None): form = PostForm(request) form.status.data = int(form.status.data) post = None if post_id is not None: post = await Post.get_or_404(post_id) if request.method in ('POST', 'PUT') and form.validate(): title = form.title.data assert str(form.author_id.data).isdigit() if post_id is None: post = await Post.filter(title=title).first() if not post: post = Post() tags = form.tags.data content = form.content.data is_page = form.is_page.data del form.tags del form.content del form.is_page form.populate_obj(post) post.type = Post.TYPE_PAGE if is_page else Post.TYPE_ARTICLE await post.save() await post.update_tags(tags) await post.set_content(content) ok = True else: ok = False post = await post.to_sync_dict() post['tags'] = [t.name for t in post['tags']] return json({'post': post if post else None, 'ok': ok})
def PostView(request): user = CheckValidation(request) if user: if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') # saving post in database post = PostModel(user=user, image=image, caption=caption) post.save() path = os.path.join(BASE_DIR, post.image.url) client = ImgurClient( 'c83158842a9256e', 'ba219c35073b2a80347afaf222e1ebc28dcc8e1a') post.image_url = client.upload_from_path(path, anon=True)['link'] #post.image_url = cloudinary.uploader.upload(path) post.save() return redirect('/') else: form = PostForm() return render(request, 'post.html', {'form': form}) else: return redirect('/login/')
def post_edit(request, id): instance = get_object_or_404(post, id=id) if request.user.id == instance.author_id: args = {} instance = get_object_or_404(post, id=id) args.update(csrf(request)) if request.method == "POST": form = PostForm(request.POST, request.FILES, instance=instance) args["err"] = form.errors if form.is_valid(): instance = form.save(commit=False) instance.author_id = request.user.id instance.save() return HttpResponseRedirect('/dashboard') args["form"] = PostForm(instance=instance) args["form_title"] = "Edit Article" return render(request, 'register.html', args, RequestContext(request)) else: context = { "msg": "You are not allowed to perform this action", "show": "alert-danger" } return render(request, 'dashboard.html', context)
def post(request): '''process post page judge user's authenticate status and save valid post, store raiseNUMBER of user''' if request.user.is_authenticated(): form = PostForm() if request.method == "POST": form = PostForm(request.POST.copy()) if form.valid(): poster = request.user title = form.cleaned_data["title"] content = form.cleaned_data["content"] bonus = form.cleaned_data["bonus"] deadline = form.cleaned_data["deadline"] post = Mission(missionNAME=title, missionDESCRIBE=content, logDATE=datetime.datetime.now(), deadline=deadline, rpBONUS=bonus, missionRAISER=poster, closed=False) post.save() poster_pro = UserProfile.objects.get(user_id=request.user.id) poster_pro.raiseNUMBER += 1 poster_pro.save() return HttpResponseRedirect("/") form = PostForm() return render_to_response("tasks/post.html",{'request': request, 'form': form, }) return HttpResponseRedirect("/accounts/login/")
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 add_post(request): if request.method == "POST": post_form = PostForm(request.POST, request.FILES) if post_form.is_valid(): title = post_form.cleaned_data['title'] keywords = post_form.cleaned_data['keywords'] description = post_form.cleaned_data['description'] image = post_form.cleaned_data['image'] text = post_form.cleaned_data['text'] slug = title new_post = Post(title=title, userid=request.user, slug=slug, keywords=keywords, image=image, text=text, description=description, date=datetime.now()) new_post.save() post_form = PostForm() return render(request, 'blog/add_post.html', {'post_form': post_form}) else: post_form = PostForm() ctx = {'post_form': post_form} return render(request, 'blog/add_post.html', ctx, )
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 new_post(request, thread_id): thread = get_object_or_404(Thread, pk=thread_id) if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(False) post.thread = thread post.user = request.user post.save() messages.success(request, "Your post has been added to the thread!") return redirect(reverse('thread', args={thread.pk})) else: form = PostForm() args = { 'form': form, 'form_action': reverse('new_post', args={thread.id}), 'button_text': 'Update Post' } args.update(csrf(request)) return render(request, 'forum/post_form.html', args)
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 post_view(request, id=None): post_sent = None post_title = None post_update = None post = None user_name = request.user.username form = PostForm() if id: post = get_object_or_404(Post, id=id) form = forms.PostForm(instance=post) post_update = True if request.method == 'POST': form = forms.PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) tags = form.cleaned_data['tags'] post.author = request.user post.save() for tag in tags: post.tags.add(tag) post_title = post.title post_sent = True return render( request, 'BlogApp/post_form.html', { 'form': form, 'post_sent': post_sent, 'post_title': post_title, 'post_update': post_update })
def new(request): from board.utils import obj token = request.POST.get('token', None) or request.GET.get('token', None) old = dict(mongo.previews.find_one({'token': token})) if token else {} form = PostForm(request.POST, obj(old)) if request.method == "POST" and form.validate(): token = request.POST.get('token', token) job = {"title": form.title.data, "job_type": form.job_type.data, "date": datetime.datetime.now(), "description": form.description.data, "how_apply": form.how_apply.data, "email": form.email.data, "location": form.location.data, "url": form.url.data, "logo_url": form.logo_url.data, "company": form.name.data, "category": form.category.data, "token": token or uuid.uuid4().hex} if token: mongo.previews.update({'token': token}, job) else: mongo.previews.insert(job) if 'jobs' not in request.session: request.session['jobs'] = [] request.session['jobs'].append(job['token']) return HttpResponseRedirect("%s?token=%s" % (reverse('preview'), job['token'])) return { 'form': form, 'token': token}
def post_view(request): user = check_validation(request) if user: if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image, caption=caption) post.save() path = str(BASE_DIR + '/' + post.image.url) client = ImgurClient( '37e25d0cbc857c0', 'f7a8c883baef922700e185d6b987a607c7a56840') post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() return redirect('/feed/') else: form = PostForm() return render(request, 'post.html', {'form': form}) else: return redirect('/login/')
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(request): if request.method == 'POST': bound_form = PostForm(request.POST) if bound_form.is_valid(): Post.objects.create(content=request.POST['content']) context = {'posts': Post.objects.all()} return render(request, 'posts/all.html', context)
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 sign(request): form = PostForm(request.POST) if form.is_valid(): post = Post(author=form.cleaned_data["author"], message=form.cleaned_data["message"]) post.put() return HttpResponseRedirect("/")
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)