예제 #1
0
def new_art():
	db.connect()
	# logging.error()
	art = ArticleForm(request.form)
	# for a in art:
		# logging.error(a)
	
	if request.method == 'POST':
		if art.validate():
			#存入数据库
			db.insert_one(table_name = 'arts',
				art_tuple = (str(uuid.uuid1()),
				request.form['title'],
				request.form['author'],
				request.form['content'],
				datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
			# db.insert_one(table_name = 'arts',art_tuple = ('art.title',"art.author","art.content"))
			logging.error('new art added')

	db_query_arts = db.find_all('arts')
	arts = []
	for db_query_art in db_query_arts:
		arts.append(Art(db_query_art[0],db_query_art[1],db_query_art[2],db_query_art[3],db_query_art[4]))

	arts.reverse()
	return render_template('new_art.html',form = art,arts = arts)
예제 #2
0
def update_article(article_id):
    article = Article.query.get_or_404(article_id)

    form = ArticleForm()

    if form.validate_on_submit():
        article.name = form.data.name
        article.note = form.data.note
        article.year_posted = form.data.year_posted
        article.count_of_pages = form.data.count_of_pages
        article.author = form.data.author
        article.type_of_art = form.data.type_of_art
        article.save()

        flash('Article updated succsesfully')

    elif request.method == 'GET':
        form.name.data = article.name
        form.note.data = article.note
        form.year_posted.data = article.year_posted
        form.count_of_pages.data = article.count_of_pages
        form.author.data = article.author
        form.type_of_art.data = article.type_of_art

    return render_template('create_article.html',
                           title='Edit article',
                           form=form,
                           action='Edit article')
예제 #3
0
def edit_article(postID):
    post = Post().query.get(int(postID))
    form = ArticleForm()
    if not post:
        flash('No such article Found !', 'error')
        return redirect(url_for('file_not_found(404)'))

    if current_user.username == post.author:
        if form.validate_on_submit():
            post.heading = form.heading.data
            post.body = form.body.data
            post.timestamp = datetime.utcnow()
            db.session.commit()
            flash('Your article has been successfully updated !', 'success')
            return redirect(url_for('dashboard'))
        elif request.method == 'GET':
            form.heading.data = post.heading
            form.body.data = post.body
        return render_template('user/edit_article.html',
                               post=post,
                               title='Edit Article',
                               form=form)
    else:
        flash(
            'You are not the author of this article.\n If you want any changes in this article please contact Administrator through Contact Page.',
            'error')
        return redirect(url_for('blog'))
예제 #4
0
파일: article.py 프로젝트: xuhao1108/Blog
def update(id):
    """
    删除文章
    :param id: 文章id
    :return:
    """
    # 获取此id的文章模型对象
    a = Article.query.filter_by(id=id).first()
    # 判断当前用户是否发表文章的用户
    if current_user == a.user:
        # 创建文章表单对象
        form = ArticleForm()
        if form.validate_on_submit():
            # 获取修改后的数据
            a.title = form.title.data
            a.body = form.body.data
            a.last_modify = datetime.datetime.utcnow()
            # 提交到数据库中
            db.session.add(a)
            db.session.commit()
            flash('修改成功!')
            return redirect(
                request.args.get('next')
                or url_for('.all', username=current_user.username))
        else:
            # 将原数据填充到表单中
            form.title.data = a.title
            form.body.data = a.body
        return render_template('article/write.html', form=form)
    else:
        abort(404)
예제 #5
0
파일: views.py 프로젝트: trncaqch/GYouMag
def add_article(request, category_name_slug):

    try:
        cat = Category.objects.get(slug=category_name_slug)
    except Category.DoesNotExist:
                cat = None

    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            if cat:
                article = form.save(commit=False)
                article.category = cat
                article.views = 0
                article.save()
                # probably better to use a redirect here.
                return category(request, category_name_slug)
        else:
            print form.errors
    else:
        form = ArticleForm()

    context_dict = {'form':form, 'category': cat}

    return render(request, 'app/add_article.html', context_dict)
예제 #6
0
def edit_article(id):
    cur = mysql.connection.cursor()
    result = cur.execute('SELECT * FROM articles WHERE id=%s', [id])
    article = cur.fetchone()

    form = ArticleForm(request.form)

    # populating form
    form.title.data = article['title']
    form.body.data = article['body']

    if request.method == 'POST' and form.validate():
        title = request.form['title']
        body = request.form['body']

        # creating cursor
        cur = mysql.connection.cursor()

        app.logger.info(title)

        cur.execute('UPDATE articles SET title=%s, body=%s WHERE id=%s',
                    (title, body, id))
        mysql.connection.commit()
        cur.close()
        flash('Article Updated', 'success')
        return redirect(url_for('dashboard'))

    return render_template('edit_article.html', name='Article', form=form)
예제 #7
0
def add_article(article_id, issue_id):
    if not current_user.is_admin:
        abort(401)

    session = new_session()

    article = Article()

    form = ArticleForm()

    if form.validate_on_submit():
        article.title = form.title.data
        session.add(article)
        session.commit()

        author = session.query(Person)\
                        .filter(Person.name == form.author.data)\
                        .first()
        auth = ArticleAuthor(article_id=article.id, person_id=author.id)
        session.add(auth)
        session.commit()

        save_tags(session, form.tags.data, "Article", article.id)

        return render_template('article', article_id=article.id)
    else:
        app.logger.debug("pubid={}".format(form.pubseries.data))
        app.logger.debug("Errors: {}".format(form.errors))

    return render_template('edit_article.html', form=form)
예제 #8
0
파일: views.py 프로젝트: okzuo3/himawari
 def edit(request, article_id):
     """Renders the article edit page."""
     try:
         article = Article.objects.get(pk=article_id)
     except Article.DoesNotExist:
         raise Http404("Article does not exist")
     if request.method == 'POST': # フォームが提出された
         form = ArticleForm(request.POST, instance = article) # POST データの束縛フォーム
         if form.is_valid(): # バリデーションを通った
             article = form.save(commit=False)
             if form.cleaned_data['no_expired_at'] is True:
                 article.expired_at = None
             article.save()
             return HttpResponseRedirect(reverse('article_list')) # POST 後のリダイレクト
     else:
         no_expired_at = False
         if article.expired_at is None:
             no_expired_at = True
             article.expired_at = datetime.now() + timedelta(days=1)
         form = ArticleForm(instance = article, initial = {'no_expired_at': no_expired_at, }) # 非束縛フォーム
     article_list = Article.objects.order_by('-released_at')[:5]
     auth_form = AuthenticationForm(None, request.POST or None)
     return render(request, 'app/article_edit.html', { 
         'form': form,
         'title':'ニュース記事の編集',
         'year':datetime.now().year,
         'articles':article_list,
         'blogs':EntryView.get_entry_list('-posted_at',-1, request.user.pk )[:5],
         'submit_title':'更新する',
         'article_pk':article.pk,
         'auth_form':auth_form,
         'current_user':request.user,
     })
예제 #9
0
def article_change(id):
    form = ArticleForm()

    if request.method == 'GET':
        article = Article.query.filter(Article.id == id).first()
        return render_template('back/article-change.html',
                               article=article,
                               form=form)
    if request.method == 'POST':
        if form.validate_on_submit():
            article = Article.query.filter(Article.id == id).first()
            article.title = form.data.get('title')
            article.body = form.data.get('body')
            article.desc = form.data.get('desc')
            article.keywords = form.data.get('keywords')
            article.c_name = form.data.get('category')
            # TODO: 如果栏目不存在,就调转到添加页面
            article.save()
            articles = Article.query.all()
            return render_template('back/article',
                                   articles=articles,
                                   message='删除成功')
        errors = form.errors
        return render_template('back/article-change.html',
                               errors=errors,
                               form=form)

    if request.method == 'DELETE':
        # 实现文章栏目
        article = Article.query.filter(Article.id == id).first()
        article.delete()
        # categorys = Category.query.all()
        data = {'code': 200, 'msg': '删除成功'}
        return jsonify(data)
예제 #10
0
def article(article_id):
    article = Article.query.filter_by(id=article_id).first()
    article_form = ArticleForm()
    if article is not None:
        if request.method == 'GET':
            return render_template('article.html', article=article, article_form=article_form)
        else:
            if logged_in() and admin():
                if request.method == 'PUT':
                    if article_form.validate_on_submit():
                        article.title = request.form['title']
                        article.body = request.form['body']
                        db.session.commit()
                        flash('Article modified successfully', 'success')
                        return redirect('/news/article' + str(article_id))
                    else:
                        flash_errors(article_form)
                        return render_template('article.html', article=article, article_form=article_form)
                elif request.method == 'DELETE':
                    db.session.delete(article)
                    db.session.commit()
                    flash('Article deleted successfully', 'success')
                    return redirect('/news')
    else:
        return render_template('404.html')
예제 #11
0
def publish():
    form = ArticleForm(request.form)
    if request.method == "GET":
        return render_template("control/publish.html", form=form)

    if form.validate_on_submit():
        # 获取博客内容
        TextContent = request.form.get("TextContent")

        # 获取上传的文件,并对图片进行预处理,上传到七牛云,然后获取url地址
        poster = None
        if request.files.get('poster'):
            file = request.files.get('poster')
            imgData = get_specification_image(file)
            poster = uploadImg(imgData)

        with db.submit_data():
            data = Article()
            data.setter_data(request.form)
            data.body = TextContent
            data.poster = poster
            db.session.add(data)
        return redirect(url_for('web.index'))
    else:
        for errorMessage in form.errors:
            flash(errorMessage)
        return redirect(url_for('web.publish'))
예제 #12
0
def article_update(id):
    article = Article.query.get(id)
    form = ArticleForm(request.form, obj=article)
    if request.method == 'POST':
        if form.validate_on_submit():
            form.populate_obj(article)
            db.session.commit()
        return redirect(url_for('article_detail', id=id))

    return render_template('article/update.html', form=form)
예제 #13
0
def article():
    form = ArticleForm()
    if form.validate_on_submit():
        article = Article(username=current_user.username,
                          author=form.author.data,
                          article_title=form.title.data,
                          article_body=form.article.data)
        db.session.add(article)
        db.session.commit()
        flash('已发布')
        return redirect(url_for("index"))
    return render_template('article.html', title='新建文章', form=form)
예제 #14
0
파일: routes.py 프로젝트: Phoenix-ssr/blog
def article():
    form = ArticleForm()
    t = time.strftime('%Y.%m.%d.%A.%H:%M:%S', time.localtime(time.time()))
    if form.validate_on_submit():
        article = Article(head=form.head.data,
                          title=form.title.data,
                          body=form.body.data,
                          author=current_user,
                          time=t)
        db.session.add(article)
        db.session.commit()
        flash('你的提交已变更.')
        return redirect(url_for('index'))
    return render_template('article.html', form=form)
예제 #15
0
def revise(article_title):
    form = ArticleForm()
    article = Article.query.filter_by(
        article_title=article_title).first_or_404()
    if form.validate_on_submit():
        article.author = form.author.data
        article.article_title = form.title.data
        article.article_body = form.article.data
        db.session.commit()
        flash('已修改')
        return redirect(url_for("index"))
    elif request.method == 'GET':
        form.author.data = article.author
        form.title.data = article.article_title
        form.article.data = article.article_body
    return render_template('article.html', title='修改文章', form=form)
예제 #16
0
def edit_article(id: Any) -> Any:
    if not current_user.is_admin:
        abort(401)

    session = new_session()

    article = session.query(Article)\
                     .filter(Article.id == id)\
                     .first()

    authors = session.query(Person)\
                     .join(ArticleAuthor)\
                     .filter(ArticleAuthor.article_id == id)\
                     .all()

    people = session.query(Person)\
                    .join(ArticlePerson)\
                    .filter(ArticlePerson.article_id == id)\
                    .all()
    links = session.query(ArticleLink)\
                   .filter(ArticleLink.article_id == id)\
                   .all()

    form = ArticleForm(request.form)

    if request.method == 'GET':
        tags = session.query(Tag.name)\
                      .join(ArticleTag)\
                      .filter(Tag.id == ArticleTag.tag_id)\
                      .filter(ArticleTag.article_id == id)\
                      .all()

        form.title.data = article.title
    if form.validate_on_submit():
        article.title = form.title.data
        session.add(article)
        session.commit()
        return redirect(url_for('article', id=article.id))
    else:
        app.logger.debug('Errors: {}'.format(form.errors))

    return render_template('article.html',
                           form=form,
                           article=article,
                           authors=authors,
                           people=people,
                           links=links)
예제 #17
0
파일: article.py 프로젝트: xuhao1108/Blog
def write():
    """
    添加文章
    :return:
    """
    form = ArticleForm()
    if form.validate_on_submit():
        # 创建文章的模型对象
        a = Article(title=form.title.data,
                    body=form.body.data,
                    username=current_user.username)
        # 添加到数据库中
        db.session.add(a)
        db.session.commit()
        flash('发布成功!')
        return redirect(url_for('.all', username=current_user.username))
    return render_template('article/write.html', form=form)
예제 #18
0
def add_article():
    form = ArticleForm()
    postcategories = PostCategory().query.all()
    tags = Tag().query.all()

    if form.validate_on_submit():
        category = PostCategory().query.filter_by(
            category_name=request.form['post-category-selector']).first()

        article = Post(heading=form.heading.data,
                       author=current_user.username,
                       timestamp=datetime.utcnow(),
                       body=form.body.data,
                       thumbnail=request.form['thumbnail'])

        string = request.form['tags'] + ','
        tag_list = []
        char = []
        for i in string:
            if i != ',':
                char.append(i)
            elif i == ',':
                char = ''.join(char)
                char = char.strip()
                get_tag = Tag.query.filter_by(tag_name=char).first()
                if get_tag is not None:
                    tag_list.append(get_tag)
                elif get_tag is None:
                    Tag().new_tag(char)
                    get_tag = Tag.query.filter_by(tag_name=char).first()
                    if get_tag is not None:
                        tag_list.append(get_tag)

                char = []

        article.tags = tag_list
        category.posts.append(article)
        db.session.commit()
        flash('Your Article has been successfully added !', 'success')
        return redirect(url_for('dashboard'))
    return render_template('user/add_article.html',
                           title='Add Article',
                           form=form,
                           postcategories=postcategories,
                           tags=tags)
예제 #19
0
def add_article():
    form = ArticleForm(request.form)
    if request.method == 'POST' and form.validate():
        title = form.title.data
        body = form.body.data

        # creating cursor
        cur = mysql.connection.cursor()

        cur.execute(
            'INSERT INTO articles(title, body, author) VALUES (%s, %s, %s)',
            (title, body, session['username']))
        mysql.connection.commit()
        cur.close()
        flash('Article created', 'success')
        return redirect(url_for('dashboard'))

    return render_template('add_article.html', name='Article', form=form)
예제 #20
0
def update_article(slug):
    article = Article.query.filter_by(slug=slug).first_or_404()
    user_id = request.cookies.get('owner_id')
    if not article.is_owner(user_id):
        abort(401)

    if request.method == 'GET':
        form = ArticleForm(obj=article)
        return render_template('update_article.html', form=form)
    else:
        form = ArticleForm(request.form)
        if request.method == 'POST' and form.validate():
            article.title = form.title.data
            article.signature = form.signature.data
            article.body = form.body.data
            db.session.commit()
            return redirect(slug)
        return render_template('update_article.html', form=form)
예제 #21
0
def create():
    form = ArticleForm()
    if form.validate_on_submit():
        if form.image.data:
            filename = upload_image(form.image.data)
        else:
            filename = ""
        category = Category.query.get(int(form.category.data))
        # store article in db
        article = Article(title=form.title.data,
                          content=form.content.data,
                          category=category,
                          image=filename)
        db.session.add(article)
        db.session.commit()
        flash('New article submitted: {}, category: {}'.format(
            form.title.data, category.name))
        return redirect(url_for('index'))
    return render_template('create.html', title='New Article', form=form)
예제 #22
0
def showForm(request):
   if request.method == 'POST':
      form = ArticleForm(request.POST)
      if form.is_valid():
         form.save()
      return render(request, 'thanks.html')
   else:
      form = ArticleForm()
      return render(request, 'article.html', {'form': form})
예제 #23
0
def add_article():
    article_form = ArticleForm()
    if article_form.validate_on_submit():
        if Article.query.filter_by(
                title=article_form.title.data).first() is not None:
            flash('Same title already existed in the database', 'error')
        elif db.session.query(Article).filter_by(
                url=article_form.url.data).first() is not None:
            flash('Same URL already existed in the database', 'error')
        else:
            article = Article(title=article_form.title.data,
                              intro=article_form.intro.data,
                              author=current_user,
                              content=article_form.content.data,
                              url=article_form.url.data
                              if article_form.url.data.strip() != '' else None)
            db.session.add(article)
            db.session.commit()
            flash('Article submit successfully', 'ok')
    return render_template('article/editor.html', article_form=article_form)
예제 #24
0
def article(id: Any) -> Any:
    session = new_session()

    article = session.query(Article)\
                     .filter(Article.id == id)\
                     .first()

    authors = session.query(Person)\
                     .join(ArticleAuthor)\
                     .filter(ArticleAuthor.article_id == id)\
                     .all()

    people = session.query(Person)\
                    .join(ArticlePerson)\
                    .filter(ArticlePerson.article_id == id)\
                    .all()
    links = session.query(ArticleLink)\
                   .filter(ArticleLink.article_id == id)\
                   .all()

    form = ArticleForm(request.form)

    if request.method == 'GET':
        form.id.data = article.id
        form.title.data = article.title

    elif form.validate_on_submit():
        article.title = form.title.data
        session.add(article)
        session.commit()
        log_change(session, 'Article', article.id)
    else:
        app.logger.debug("Errors: {}".format(form.errors))
        print("Errors: {}".format(form.errors))

    return render_template('article.html',
                           article=article,
                           authors=authors,
                           people=people,
                           links=links,
                           form=form)
예제 #25
0
def article_create():

    form = ArticleForm()

    if request.method == 'GET':
        return render_template('article/create.html', form=form, active_tab='article_create')
    elif request.method == 'POST':
        if form.validate_on_submit():
            article = Article(
                title=form.title.data,
                author=form.author.data,
                category=form.category.data,
                content=form.content.data
            )

            db.session.add(article)
            db.session.commit()

            flash(u'게시글을 작성하였습니다.', 'success')
            return redirect(url_for('article_list'))
        return render_template('article/create.html', form=form, active_tab='article_create')
예제 #26
0
def add_article():
    form = ArticleForm()

    if request.method == 'GET':
        return render_template('back/add-article.html', form=form)
    if request.method == 'POST':
        if form.validate_on_submit():
            # 通过验证就建文章对象
            article = Article()
            article.title = form.data.get('title')
            article.body = form.data.get('body')
            article.desc = form.data.get('desc')
            article.keywords = form.data.get('keywords')
            article.c_name = form.data.get('category')
            # TODO: 如果栏目不存在,就调转到添加页面
            article.save()
            return redirect(url_for('back.article'))
        errors = form.errors
        return render_template('back/add-article.html',
                               errors=errors,
                               form=form)
예제 #27
0
파일: article.py 프로젝트: tyaathome/myblog
def add():
    form = ArticleForm(request.form)
    messages = []
    if request.method == 'POST':
        if form.validate_on_submit():
            title = form.title.data
            content = form.content.data
            if form.commit.data:
                username = request.cookies.get('username')
                if not username:
                    return redirect(url_for('index'))
                id = db.session.query(func.max(Article.id)).scalar()
                if not id:
                    id = 0
                id += 1
                tag = 'test'
                article = Article(id=id, title=title, content=content, tag=tag)
                db.session.add(article)
                db.session.commit()
                return redirect(
                    url_for('.get_user_article_by_id', user=username, id=id))
            elif form.preview.data:
                content = form.content.data
                text = Markup(markdown.markdown(content, ['extra']))
                session['content'] = content
                session['is_preview'] = True
                return render_template('/article/add_article.html',
                                       form=form,
                                       content=text)
            elif form.edit.data:
                session['is_preview'] = False
                content = session['content']
                form.content.data = content
                return render_template('/article/add_article.html', form=form)
        else:
            messages = [r for k, v in form.errors.items() for r in v]
    else:
        session['content'] = ''
        session['is_preview'] = False
    return render_template('/article/add_article.html', form=form)
예제 #28
0
파일: views.py 프로젝트: pangting/myBlog
def article_post(request):
    u_id = request.session.get('id', '')
    user = User.objects.get(id=u_id)
    if request.method == 'POST':
        article_post_form = ArticleForm(data=request.POST)
        if article_post_form.is_valid():
            print('==================')
            cd = article_post_form.cleaned_data
            new_article = article_post_form.save(commit=False)
            new_article.author = User.objects.get(id=u_id)
            # print(request.user.id)
            # 获取下拉框选择的分类id
            cate = request.POST['c_category']
            # print(cate)
            new_article.category = Category.objects.get(id=cate)
            new_article.save()
            return redirect(reverse('blog:blog_index'))
    else:
        article_post_form = ArticleForm()
        # cate = Category.objects.all()
        # print(cate)
        article_categorys = Category.objects.all()
        print('=======', article_categorys)
        return render(request, 'blog/article_post.html',
                      {'article_post_form': article_post_form, 'article_categorys': article_categorys, 'user': user})
예제 #29
0
def article_add_edit(article_id=None):
    if 'authenticated' not in session:
        return redirect('/login')
    form = ArticleForm()
    form.init()
    print(form.authors.choices)
    if form.validate_on_submit():  # it's submit!
        form.save_to_db()
        return redirect('/articles')
    else:  # either edit or add
        if article_id:  # populate first for edit
            form.load_from_db(article_id)

    return render_template('article_edit_or_add.html',
                           page='article_edit_or_add',
                           title='Άρθρα',
                           cdn=cdn,
                           form=form)
예제 #30
0
def new_article():
    form = ArticleForm()

    if form.validate_on_submit():
        print("ZZZ")
        title = form.title.data
        time_now = datetime.now()
        folder_name = form.identifier.data

        new_object = Article()
        new_object.title = title
        new_object.created = time_now
        new_object.updated = time_now
        new_object.folder = folder_name
        new_object.author = g.user

        db.session.add(new_object)
        db.session.commit()

        return redirect(url_for('admin.index'))

    return render_template('admin/article.html', form=form)
예제 #31
0
def view_article(art_id):
    article = Article.query.get(art_id)
    form = ArticleForm()

    if form.validate_on_submit():
        title = form.title.data
        time_now = datetime.now()
        folder_name = form.identifier.data

        new_object = Article()
        new_object.title = title
        new_object.updated = time_now

        db.session.add(new_object)
        db.session.commit()

        return redirect(url_for('admin.index'))

    return render_template(
        'admin/article_detail.html',
        article=article,
    )
예제 #32
0
def new_article():
    form = ArticleForm()

    if form.validate_on_submit():
        name = form.name.data
        note = form.note.data
        author = form.author.data
        year_posted = form.year_posted.data
        count_of_pages = form.count_of_pages.data
        type_of_art = form.type_of_art.data

        article = Article(name, year_posted, count_of_pages, author, note,
                          type_of_art)
        article.save()

        flash('Article created successfully', 'success')
        return redirect(url_for('article', article_id=article.id))

    return render_template('create_article.html',
                           title='Create new article',
                           form=form,
                           action='Create new article')
예제 #33
0
def article_create():
    form = ArticleForm()
    if request.method == 'GET':
        return render_template('article/create.html', form=form, active_tab='article_create')

    elif request.method == 'POST':
        if form.validate_on_submit():
            # 사용자가 입력한 글 데이터로 Article모델 인스턴스 생성
            article = Article(
                title=form.title.data,
                author=form.author.data,
                category=form.category.data,
                content=form.content.data
            )
            # 데이터베이스에 데이터를 저장할 준비를 한다
            db.session.add(article)
            # 데이터베이스에 저장하라는 명령을 한다
            db.session.commit()

            flash(u'게시글 업로드를 완료하였습니다.', 'success')
            return redirect(url_for('article_list'))
        return render_template('article/create.html', form=form, active_tab='article_create')
예제 #34
0
def article(article_id):
    if (article_id == None):
        return redirect(url_for('index'))
    else:
        art = Article.query.filter_by(id=article_id).first()
        if (art == None):
            abort(404)
    form = ArticleForm()
    if form.validate_on_submit():
        if not (current_user.is_authenticated):
            return redirect(url_for('login'))
        if form.like.data:
            if (str(current_user.id)
                    not in (art.likedusers.split() if art.likedusers else [])):
                art.likes += 1
                art.likedusers = (art.likedusers if art.likedusers else
                                  "") + str(current_user.id) + " "
                db.session.commit()
            else:
                return render_template(
                    'article.html',
                    article=art,
                    form=form,
                    message="You have already liked this article!")
        elif form.readlater.data:
            if (str(art.id) not in (current_user.articles.split()
                                    if current_user.articles else [])):
                if current_user.articles:
                    current_user.articles += " " + str(art.id)
                else:
                    current_user.articles = str(art.id)
                db.session.commit()
            else:
                return render_template(
                    'article.html',
                    article=art,
                    form=form,
                    message="This article has already been marked!")
    return render_template('article.html', article=art, form=form)
예제 #35
0
def articleEdit(aid):
    article = Article.query.get(aid)
    form = ArticleForm(request.form)
    tags = [item.tag.name for item in article.tags]

    if request.method == 'POST' and form.validate():
        article.title = form.title.data
        article.content = form.content.data
        article.category = Category.query.filter_by(name=form.category.data).first()

        updateTags = form.tags.data.split(',')

        # 将新标签写入数据库,并为文章添加新标签
        newTags = form.newTags.data
        if newTags:
            for t in newTags.split(','):
                if not Tag.exist(t):
                    tag = Tag(name=t.strip())
                    db.session.add(tag)
                    article.addTag(tag)

        # 对文章已有标签检测是否有更改
        tagsNeedDel = list(set(tags).difference(set(updateTags)))  # 需要移除的 tag
        tagsNeedAdd = list(set(updateTags).difference(set(tags)))  # 需要添加的 tag

        # 添加
        for t in tagsNeedAdd:
            tag = Tag.query.filter_by(name=t.strip()).first()
            article.addTag(tag)

        # 删除
        for t in tagsNeedDel:
            tag = Tag.query.filter_by(name=t.strip()).first()
            article.delTag(tag)

        db.session.commit()
        return redirect(url_for('admin.articles'))
    return render_template('admin/articleWrite.html', form=form, article=article, tags=tags)
예제 #36
0
def news_index(page=1):
    articles_query = Article.query.order_by('id desc')
    articles_paginate = articles_query.paginate(page, 5, False)
    articles = articles_paginate.items
    article_form = ArticleForm()
    if request.method == 'GET':
        if articles_paginate.pages != 0 and articles_paginate.pages < page:
            return redirect('/news')
        return render_template('news.html', article_form=article_form, articles=articles)
    else:
        if logged_in() and admin():
            if article_form.validate_on_submit():
                user = current_user()
                new_article = Article(request.form['title'], request.form['body'])
                new_article.user_id = user.id
                user.articles.append(new_article)
                db.session.add(new_article)
                db.session.commit()
                flash('Article posted successfully', 'success')
                return redirect('/news')
            else:
                flash_errors(article_form)
                return render_template('news.html', article_form=article_form, articles=articles)
예제 #37
0
def create_article():
    form = ArticleForm(request.form)
    if request.method == 'POST' and form.validate():
        dt = datetime.now()
        slug = slugify('{}-{}-{}-{}-{}-{}'.format(dt.month, dt.day, dt.hour,
                                                  dt.minute, dt.second,
                                                  form.title.data),
                       max_length=255,
                       save_order=True)
        owner_id = request.cookies.get('owner_id')
        if owner_id == 'undefined' or owner_id is None:
            owner_id = str(uuid.uuid4())
        article = Article(title=form.title.data,
                          signature=form.signature.data,
                          body=form.body.data,
                          slug=slug,
                          owner_id=owner_id)
        db.session.add(article)
        db.session.commit()
        response = current_app.make_response(redirect(slug))
        response.set_cookie('owner_id', owner_id)
        return response
    return render_template('create_article.html', form=form)
예제 #38
0
파일: views.py 프로젝트: okzuo3/himawari
 def new(request):
     """Renders the new article page."""
     if request.method == 'POST': # フォームが提出された
         form = ArticleForm(request.POST) # POST データの束縛フォーム
         if form.is_valid(): # バリデーションを通った
             article = form.save(commit=False)
             if form.cleaned_data['no_expired_at'] is True:
                 article.expired_at = None
             article.save()
             return HttpResponseRedirect(reverse('article_list')) # POST 後のリダイレクト
     else:
         form = ArticleForm() # 非束縛フォーム
     article_list = Article.objects.order_by('-released_at')[:5]
     auth_form = AuthenticationForm(None, request.POST or None)
     return render(request, 'app/article_edit.html', { 
         'form': form,
         'title':'ニュース記事の新規登録',
         'year':datetime.now().year,
         'articles':article_list,
         'blogs':EntryView.get_entry_list('-posted_at',-1, request.user.pk )[:5],
         'submit_title':'登録する',
         'auth_form':auth_form,
         'current_user':request.user,
     })
예제 #39
0
def update(id):
    article = Article.query.get(id)
    form = ArticleForm()
    if form.validate_on_submit():
        if form.image.data:
            # first delete image from upload folder!
            delete_upload_image(article.image)
            # upload new image
            filename = upload_image(form.image.data)
            article.image = filename
        article.title = form.title.data
        article.content = form.content.data
        article.category = Category.query.get(int(form.category.data))
        db.session.commit()
        flash("Your changes have been saved.")
        return redirect(url_for('index'))
    elif request.method == "GET":
        form.title.data = article.title
        form.content.data = article.content
        form.category.data = str(article.category.id)
    return render_template('update.html',
                           title='Edit Article',
                           form=form,
                           article=article)
예제 #40
0
def article_create():
    if g.user_name is None:
        flash(u'로그인 후에 이용해 주세요', 'danger')
        return redirect(url_for('login'))
    else:
        form = ArticleForm()

        if request.method == 'POST':
            if form.validate_on_submit():

                article = Article(
                    title=form.title.data,
                    # author=form.author.data,
                    author=g.user_name,
                    category=form.category.data,
                    content=form.content.data
                )

                db.session.add(article)
                db.session.commit()

                flash(u'게시글 작성하였습니다.', 'success')
                return redirect(url_for('article_list'))
        return render_template('article/create.html', form=form, active_tab='article_create')