Kod Wykop

mail@pastecode.io avatar
unknown
python
2 years ago
2.2 kB
8
Indexable
Never
post_tags = Table('post_tags', Base.metadata,
    Column('post_id', Integer, ForeignKey('post.id')),
    Column('tag_nametag', Text, ForeignKey('tag.nametag'))
)

class Post(Base):
    __tablename__ = 'post'
    id = Column(Integer, primary_key = True, autoincrement='auto')
    author_id = Column(Integer, ForeignKey('user.id'),nullable=False)
    created = Column(DateTime, nullable = False, default = datetime.now().date())
    score = Column(Integer, nullable = False, default = 0)
    title = Column(Text, nullable = False, unique = True)
    body = Column(Text, nullable = False)

    tags = relationship('Tag', secondary = post_tags,back_populates= 'posts')
    
    def __repr__(self):
        return '<Post %r>' % self.title
    
class Tag(Base):
    __tablename__ = 'tag'
    id = Column(Integer, autoincrement='auto')
    nametag = Column(Text, primary_key = True)
    posts = relationship('Post', secondary = post_tags, back_populates = 'tags')
    
    def __repr__(self):
        return '<Tag %r>' % self.nametag


@bp.route("/create", methods=("GET", "POST"))
@login_required
def create():
    """Create a new post for the current user."""
    if request.method == "POST":
        title = request.form["title"]
        body = request.form["body"]
        tags = request.form["tags"].lower()
        new_tags = tags.split(' ')
        error = None

        if not title:
            error = "Title is required."

        if error is not None:
            flash(error)
        else:
            add_post = Post(title= title,body = body, author_id = g.user.id)

            if tags is not None:
                for i in new_tags:
                    try:
                        add_post.tags.append(Tag(nametag=i))
                        db.session.add(add_post)
                        
                    except SQLAlchemyError as e:
                        print(e)
                        pass
                db.session.add(add_post)
                db.session.commit()
                print('Tags: ', tags)

            return redirect(url_for("blog.index"))

    return render_template("blog/create.html")