简体   繁体   English

如何在 Flask 应用程序中正确更新博客文章上的标签?

[英]How to update properly tags on a blog post in Flask app?

I have a taking notes system where each note can be associate with one or many tags.我有一个笔记系统,其中每个笔记都可以与一个或多个标签相关联。

Here is my model for that part:这是我的 model 部分:

tags = db.Table('tags',
                db.Column('tag_id', db.Integer, db.ForeignKey(
                    'tag.id'), primary_key=True),
                db.Column('notes_id', db.Integer, db.ForeignKey(
                    'notes.id'), primary_key=True)
                )


class Notes(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    # ...
    tags = db.relationship('Tag', secondary=tags, lazy='subquery',
                           backref=db.backref('notes', lazy=True))


class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=None)

    def __init__(self, name):
        self.name = name

I would like to remove the tags that are no longer associated with my note when I update this note.我想在更新此笔记时删除不再与我的笔记关联的标签。 How can I do that?我怎样才能做到这一点?

For instance, it's what I have:例如,这就是我所拥有的:

@bp.route('/update/<int:id>', methods=['GET', 'POST'])
@login_required
def update(id):
    note = Notes.query.get_or_404(id)

    tags = []
    for e in note.tags:
        tag = Tag.query.get_or_404(e.id)
        tags.append(tag.name)
    tags = ', '.join(tags)

    if request.method == 'POST':
        note.title = request.form.get('title')
        note.content = request.form.get('content')
        note.updated_at = datetime.now()

        # Get a tags list from an input and convert it to string
        tags = request.form.get('tags').split(', ')

        if tags:
            for tag in tags:
                tag_exists = Tag.query.filter_by(name=tag).first()
                if not tag_exists:
                    new_tag = Task(tag)
                    db.session.add(new_tag)
                    note.tags.append(new_tag)
                else:
                    db.session.add(tag_exists)
                    note.tags.append(tag_exists)

        # Want to check if I have to delete tags associations here..

        db.session.add(note)
        db.session.commit()
        return redirect(url_for('notes.index'))
    else:
        if note.owner_id == int(current_user.get_id()):
            return render_template('notes/update.html', note=note, tags=tags)
        else:
            flash("You can't update a page which is not yours", "error")
            return redirect(url_for('notes.index'))

I know my code is a bit dirty but it's my first real app with Flask, I do my best我知道我的代码有点脏,但这是我第一个使用 Flask 的真正应用程序,我尽我所能

Thank you for help谢谢你的帮助

Here is an example, hope this helps这是一个例子,希望这有帮助

# find note which you want change
note = Notes.query.get(3)
# find tag which you want delete
tag = note.tags[0]
note.tags.remove(tag)
db.session.add(note)
db.session.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 flask app无法正确呈现html标签 - flask app not rendering html tags properly 如何将 slug 添加到 Flask 博客应用程序 - How to add slug to flask blog app 烧瓶-如何正确测试POST? - Flask - how to test POST properly? 如何摆脱烧瓶博客中的帖子? - How do I get rid of a post from a flask blog? 如何在Heroku上运行的Flask应用程序的/ blog Directoy上使用Wordpress - How to have Wordpress on a /blog directoy of a Flask app running on Heroku Flask 博客文章广泛的控件 - 如何控制文本格式、添加链接、图片等的能力 - Flask blog post extensive controls - How to control text formating, ability to add links, pictures etc 如何创建一个 Django model function 来返回博客帖子的读取时间,如果正文有 ZFC365FDC70D5267D - How to create a Django model function that returns the read time of a blog Post, if the body has html tags in it? Flask + SQLAlchemy + Google Ads API:如何正确更新刷新令牌? - Flask + SQLAlchemy + Google Ads API : How to properly update refresh token? 如何在Apache托管的Flask网站上拥有一个在/ blog上的WordPress博客? - How to have an Apache-served Flask website with a WordPress blog at /blog? 从登录的用户那里获取特定的博客文章 - 使用 Flask 和 sqlalchemy - Getting the specific blog post from the user that is logged in - with flask and sqlalchemy
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM