def tag(): if request.method == 'POST': form = TagForm() if form.new_row.data: form.img_tag.append_entry() elif form.submit.data: if form.validate_on_submit(): key_array = [] for key in request.files.keys(): key_array.append(key) for idx in range(0, len(request.files)): tags = form.img_tag.data[idx]['tag'].split(",") images = request.files.getlist(key_array[idx]) for img in images: filename = save_file(img) add_and_tag_file(filename, form.project.data, tags) os.remove( os.path.join(app.config['UPLOAD_FOLDER'], filename)) iteration_info = train_project(form.project.data) flash('Files uploaded') return render_template('train_result.html', info=iteration_info) flash('No files were uploaded') return render_template('tag.html', form=form) form = TagForm() return render_template('tag.html', form=form)
def taggremaker(): """ Page to generate taggregator iframe. Starts with example iframe for tumblr user airdeari. Uses TagForm to make a new taggregation for the tumblr user and styling of choice. :return: the page I just described """ u = "airdeari" c = "fffafb" h = 200 w = 300 iframe_code = '<iframe src="http://iraedria.ksadwin.com' +\ url_for('taggregator', username=u, color=c, height=h, width=w) +\ '" frameBorder="0" scrolling="no"></iframe>' f = TagForm() if f.validate_on_submit(): u = f.username.data c = f.color.data h = f.height.data w = f.width.data iframe_code = '<iframe src="http://iraedria.ksadwin.com' +\ url_for('taggregator', username=u, color=c, height=h, width=w) +\ '" frameBorder="0" scrolling="no"></iframe>' return render_template("tagremaker.html", form=f, u=u, c=c, w=w, h=h, iframe_code=iframe_code) # I should have just made this form myself with JS probably return render_template("tagremaker.html", form=f, u=u, c=c, w=w, h=h, iframe_code=iframe_code)
def edit_tag(id): form = TagForm() tag = Tag.query.get_or_404(id) form.name.data = tag.name if form.validate_on_submit(): pass return render_template('tag_edit.html', form=form)
def add_or_edit_memo(request, memo_form, is_edit): ''' メモを新規に追加,または既存のメモを編集する. ''' if memo_form.is_valid(): new_memo = memo_form.save(commit = False) new_memo.save() if is_edit: new_memo.tags.clear() new_memo.save() tags = request.POST['tags-text'] for stag in [s.rstrip() for s in tags.split()]: if len(Tag.objects.filter(name = stag)) == 0: tag = Tag(name = stag, user = request.user) tag_form = TagForm(instance = tag) if is_valid_tag(stag): new_tag = tag_form.save(commit = False) new_tag.save() new_memo.tags.add(new_tag) new_memo.save() else: messages.error(request, 'Incorrect tag name. ({0})'.format(stag)) else: tag = Tag.objects.get(name = stag) new_memo.tags.add(tag) new_memo.save() if is_edit: clear_notused_tag() else: messages.error(request, 'Incorrect title or content.')
def detail_view(rec_number): # создадим формы commentform = CommentForm() tagform = TagForm() # сохраним начала ключей данного оюъявления в редис tag_key = f'{rec_number}:tags' comment_key = f'{rec_number}:comments:' # выгребаем из кэша простые словари, без вложенностей bul = fish_out_of_cache_simple(r, rec_number) # если есть тэги, запрашиваем и их, но т.к. они хранятся в виде сета, то для них используется другая команда if r.scard(tag_key) > 0: bul['tags'] = [x.decode("utf-8") for x in r.smembers(tag_key)] # Выбираем из кэша комменты. Перебираем все по очереди, используя начало ключа и счетчик # когда оба запроса на предполагаемый контент вернут ничего, останавливаемся bul['comments'] = [] comment_count = 0 while True: author = r.get(f'{comment_key}{comment_count}:author') content = r.get(f'{comment_key}{comment_count}:content') if not (author and content): break comment_count += 1 bul['comments'].append({ 'author': author.decode("utf-8"), 'content': content.decode("utf-8") }) # если с формы пришли тэги, превращаем их в массив и закидываем в редис # если после этого окажется, что сэт увеличился, переписываем в сэт в бд if tagform.validate_on_submit(): new_tags = make_tags(tagform.tags.data) r.sadd(tag_key, *new_tags) if r.scard(tag_key) > len(bul['tags']): col.update_one({"_id": ObjectId(rec_number)}, { "$set": { "tags": [x.decode("utf-8") for x in r.smembers(tag_key)] } }) return redirect(url_for('detail_view', rec_number=rec_number)) # берем новый коммент с формы и записываем и в бд и в кэш if commentform.validate_on_submit(): new_comment = { "author": commentform.author.data, "content": commentform.content.data, } col.update_one({"_id": ObjectId(rec_number)}, {"$push": { "comments": new_comment }}) r.set(f'{comment_key}{comment_count}:author', new_comment['author']) r.set(f'{comment_key}{comment_count}:content', new_comment['content']) return redirect(url_for('detail_view', rec_number=rec_number)) return render_template('bul_detail.html', title='Bulletin', bul=bul, cmform=commentform, tgform=tagform)
def tags(): tag_form = TagForm() if tag_form.validate_on_submit(): tag_name = tag_form.tag_name.data tag = Tag(TagName=tag_name) db.session.add(tag) db.session.commit() flash(f"Created Tag: {tag_form.tag}") return render_template('tags.html', TagForm=tag_form)
def post_tag(): form = TagForm() user = current_user print(user.id) form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): tag = Tag(tagName=form.data['tagName'], userId=user.id) db.session.add(tag) db.session.commit() return tag.to_dict()
def tag_stream(request): response = reply_object() form = TagForm(request.POST, request=request) if form.is_valid(): response = form.tag_stream_op() else: response["code"] = settings.APP_CODE["FORM ERROR"] response["errors"] = form.errors return HttpResponse(simplejson.dumps(response))
def task(): rpp = get_random_pair_of_posts(DB) tag_form = TagForm(newsgroupA=rpp[0]['label'], newsgroupB=rpp[1]['label']) if tag_form.validate_on_submit(): tag_form_results = [tag_form.newsgroupA.data, tag_form.tagA.data, tag_form.newsgroupB.data, tag_form.tagB.data] save_results(tag_form_results, DB) flash("Thank you for entering these tags: {}:'{}', {}:'{}'".format(*tag_form_results)) return redirect(url_for('task')) return render_template('task.html', rpp=rpp, form=tag_form)
def tag(): form = TagForm() tags = Tag.query.all() if form.validate_on_submit(): name = form.name.data tag = Tag(name=name) db.session.add(tag) db.session.commit() flash('create success!', 'success') return redirect(url_for('tag')) return render_template('tag_list.html', form=form, tags=tags)
def get_tagquestions(): form = TagForm() if form.validate_on_submit(): tag = form.tag.data tag = tag.lower() print(tag) if (tag == 'dynamic programming'): tag = "dp" if (tag == 'dfs'): tag = "dfs and similar" if (tag == "mst" or tag == "minimum shortest path" or tag == "minimum shortest paths"): tag = "shortest paths" if (tag == "tree"): tag = "trees" if (tag == "graph"): tag = "graphs" if (tag == "maths"): tag = "math" if (tag == "matrix"): tag = "matrices" all_data = QuestionTags.query.filter(QuestionTags.Tag == tag).all() #dividing codechef and codeforces cc_data = [] cf_data = [] for d in all_data: qid = d.Ques_id question = Questions.query.filter(Questions.Qid == qid).first() qname = question.Qname ques_link = question.Ques_link sol_link = question.Sol_link if question.Platform == 'codechef': ques_link = Config.codechef_question_link + ques_link if sol_link: sol_link = Config.codechef_solution_link + sol_link else: sol_link = None q_data = Questiondata(qname, ques_link, sol_link) cc_data.append(q_data) elif question.Platform == 'codeforces': ques_link = Config.codeforces_question_link + ques_link sol_link = Config.codeforces_solution_link + sol_link q_data = Questiondata(qname, ques_link, sol_link) cf_data.append(q_data) return render_template('print_tagquestions.html', tag=tag, cc_data=cc_data, cf_data=cf_data) return render_template('get_tagquestions.html', form=form)
def show_tags(): all_tags = TagModel.query.all() form = TagForm(request.form) if request.method == 'POST' and form.validate(): name = request.form['name'] tag = TagModel(name=name) if TagModel.query.filter_by(name=name).first(): return render_template('owners/show_all_tags.html', tags=all_tags, form=form) db.session.add(tag) db.session.commit() return render_template('owners/show_all_tags.html', tags=all_tags, form=form)
def add_tag(): form = TagForm(request.form) if request.method == 'POST' and form.validate(): existing_tag = Tag.query.filter_by(name=form.name.data).first() if existing_tag: form.name.errors.append('Tag with such name already exists') else: tag = Tag(form.name.data) db.session.add(tag) db.session.commit() flash('Successfully added tag') return redirect(url_for('manage_tags')) return render_template('add_tag.html', form=form)
def edit_tag(tag_id): tag = Tag.query.get_or_404(tag_id) if request.method == 'POST': form = TagForm(request.form) if form.validate(): existing_tag = Tag.query.filter_by(name=form.name.data).first() if existing_tag and existing_tag.id != tag.id: form.name.errors.append('Duplicate tag, man') else: tag.name = form.name.data db.session.commit() flash('Successfully saved edits') return redirect(url_for('manage_tags')) else: form = TagForm(obj=tag) return render_template('edit_tag.html', form=form, tag=tag)
def hardadmin(request): try: if request.user.is_superuser: tagform = TagForm() if request.path.find('linking') > 0: linking() elif request.path.find('kodmod') > 0: if request.POST: tags = TagForm(request.POST) if tags.is_valid(): params = tags.cleaned_data kodmod(params['pagetype'], params['metatag'], params['metatext']) tagform = tags mdict = {'tagform':tagform.as_p, } return render_to_response("admin/admintemp.html", mdict, context_instance=RequestContext(request)) else: return HttpResponseRedirect("/admin/") except Exception as e: return HttpResponseRedirect("/404/", status=404)
def all_tags(): if request.method == 'POST': name, color = request.form['name'], request.form['color'] try: Tag.create(name=name, color=color) except Exception as e: flash(str(e), 'alert') else: flash('Тег создан', 'success') return redirect(url_for("tags.all_tags")) tags = Tag.get() form = TagForm() return render_template('tags.html', tags=tags, form=form, button='Создать')
def manage(): header = { "title": "Admin page", "subtitle": "Manage your blog!", "image_path": "manage_bg.jpg", "needed": True, "dashboard_flash": True } posts = Blogpost.query.order_by(Blogpost.date_posted.desc()).all() tags = Tags.query.all() form = TagForm() #if post request to edit form and is validated if form.validate_on_submit(): app.logger.info('tag to be added') tag = Tags(name=form.name.data) db.session.add(tag) db.session.commit() #flash message, article has been updated flash('tag uploaded', 'success') #redirect return redirect(url_for('manage')) #load template with articles return render_template('manage.html', posts=posts, header=header, tags=tags, form=form)
def edit_tag(slug): if request.method == 'POST': name, color = request.form['name'], request.form['color'] tag = Tag.get_first(slug=slug) if tag: try: tag.update(name=name, color=color) except Exception as e: flash(str(e), 'alert') else: flash('Тег обновлен', 'success') return redirect(url_for("tags.all_tags")) tags = Tag.get() form = TagForm() tag = Tag.get_first(slug=slug) if tag: form.name.data = tag.name form.color.data = tag.color return render_template('tags.html', tags=tags, form=form, button='Изменить')