Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # associates/connection table between User and books
- user_books = db.Table(
- "user_books",
- db.metadata,
- db.Column("users_id", ForeignKey("user.id"), primary_key=True),
- db.Column("books_id", ForeignKey("books.id"), primary_key=True),
- class User(UserMixin, db.Model):
- Many to Many relationship between Books
- '''
- __tablename__ = "user"
- id: Mapped[int] = mapped_column(primary_key=True)
- # unique blocks the same username etc
- # I can't have Nullable=False because it will make me add the columns everytime I add a column in User table
- username: Mapped[str] = mapped_column(String(80), index=True, unique=True)
- hashed_password: Mapped[str] = mapped_column(String(128))
- email: Mapped[str] = mapped_column(String(700), index=True)
- # Many relationship in a Many to Many relationship
- rel_books: Mapped[List['Books’]] = relationship(secondary=user_books, back_populates="rel_user")
- def __repr__(self):
- return '<User {}>'.format(self.username)
- class Books(UserMixin, db.Model):
- '''
- Many to Many relationship between User
- '''
- id: Mapped[int] = mapped_column(primary_key=True)
- book_name: Mapped[str] = mapped_column(String(120)) # todo add unique=True for all users in a function
- chapter_name: Mapped[Optional[str]] = mapped_column(String(120))
- text: Mapped[Optional[str]] = mapped_column(String())
- # connection between User table
- rel_user: Mapped[List["User"]] = relationship(secondary=user_books, back_populates="rel_books")
- def __repr__(self):
- return '<books{}>'.format(self.text)
- class CreateBookForm(FlaskForm):
- '''
- This is in the "/book/create" route.
- The form are book_name + book_chapters.
- '''
- book_name = StringField('book name', validators=[DataRequired("The book's name is required"),
- submit = SubmitField('Submit')
- # create book
- @bookroute.route('/book/create', methods = ['GET', 'POST'])
- @login_required
- def create_book():
- form = CreatebookForm()
- if form.validate_on_submit():
- book_name_form = form.book_name.data
- add_book_info = Books(book_name=book_name_form)
- db.session.add(add_books_info)
- db.session.commit()
- flash('You have created a book successfully')
- book_db = db.session.execute(db.select(Books).filter_by(book_name=book_name_form)).scalar_one_or_none()
- user_db = db.session.execute(db.select(User).filter_by(username=current_user.username)).scalar_one_or_none()
- # create an user for a book. This connects the User and Books tables.
- user_db.rel_books.append(add_book_info)
- db.session.commit()
- book_db = db.session.execute(db.select(Books).filter_by(books_name=books_name_form)).scalar_one_or_none()
- return redirect(url_for('bookroute.book', book_name_db=book_db.book_name))
- return render_template('create_book.html', title='create book’, form=form)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement