Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- app.py
- import os
- # flask imports
- from flask import Flask, flash, redirect, render_template, url_for
- from flask_sqlalchemy import SQLAlchemy
- from flask_ckeditor import CKEditor, CKEditorField
- # forms
- from flask_wtf import FlaskForm
- from sqlalchemy.orm import Mapped, mapped_column
- from wtforms import SubmitField
- from wtforms.validators import DataRequired, ValidationError
- basedir = os.path.abspath(os.path.dirname(__file__))
- # 1. Initialize Extensions (No longer importing SQLAlchemy twice)
- db = SQLAlchemy()
- # create the app
- app = Flask(__name__)
- ckeditor = CKEditor(app)
- # 2. Configuration
- app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
- app.config['SECRET_KEY']= 'secret_key'
- app.config["CKEDITOR_PKG_TYPE"] = 'full'
- app.config["CKEDITOR_EXTRA_PLUGINS"] = ['mathjax']
- # initialize the app with the extension
- db.init_app(app)
- # 3. Model Definition
- class Posts(db.Model):
- id: Mapped[int] = mapped_column(primary_key=True)
- # FIX: Use db.Text for CKEditor (long-form content)
- content: Mapped[str] = mapped_column(db.Text)
- def __repr__(self):
- # IMPROVEMENT: Safer __repr__ for long content
- return f'<Post {self.id}: {self.content[:20]}...>'
- # 5. Forms
- class CreatePostForm(FlaskForm):
- # CKEditorField is correct for rich text input
- content = CKEditorField('Content', validators=[DataRequired('Content is required')])
- submit = SubmitField('Submit')
- # 6. Routes
- @app.route('/', methods = ['GET', 'POST'])
- @app.route('/home', methods = ['GET', 'POST'])
- def home():
- form = CreatePostForm()
- if form.validate_on_submit():
- content = form.content.data
- add_postinfo = Posts(content=content)
- db.session.add(add_postinfo)
- db.session.commit()
- flash('Post created successfully!', 'success')
- return redirect(url_for('other_page')) # Redirect to the check page
- return render_template('home.html', title='Home', form=form)
- @app.route('/other_page', methods = ['GET', 'POST'])
- def other_page():
- all_posts = db.session.query(Posts).all()
- # You need to render a template here!
- # Assuming you have an 'other_page.html' template
- return render_template('other_page.html', title='Check Post', all_posts=all_posts )
- # 7. Database Creation and App Run
- if __name__ == '__main__':
- with app.app_context():
- # Ensure tables are created before running the app
- db.create_all()
- app.run(debug=True)
- templates/layout.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- {% block content %}
- {% endblock content %}
- </body>
- </html>
- templates/home.html
- {% extends "layout.html" %}
- <!-- get the error message from wtf forms -->
- {% from "_formhelpers.html" import render_field %}
- {% block title %} {{title}} {% endblock title %}
- <!-- should I use block content or an different name?-->
- {% block content %}
- <!-- Once you get the error message from ( "_formhelpers.html" import render_field) , you use novalidate to
- get the error message from wtf forms and makes it show up on the screen. %} -->
- <form action="" method="post" novalidate>
- <!-- Make the secret key work -->
- {{ form.csrf_token }}
- {{ form.content | safe }}
- <input type="submit" value="Submit">
- </form>
- {{ ckeditor.load(custom_url=url_for('static', filename='ckeditor/ckeditor.js')) }}
- {{ ckeditor.config(name='content') }}
- {% endblock content %}
- {% extends "layout.html" %}
- <!-- get the error message from wtf forms -->
- {% from "_formhelpers.html" import render_field %}
- {% block title %} {{title}} {% endblock title %}
- <!-- should I use block content or an different name?-->
- {% block content %}
- <!-- Once you get the error message from ( "_formhelpers.html" import render_field) , you use novalidate to
- get the error message from wtf forms and makes it show up on the screen. %} -->
- <form action="" method="post" novalidate>
- <!-- Make the secret key work -->
- {{ form.csrf_token }}
- {{ form.content | safe }}
- <input type="submit" value="Submit">
- </form>
- {{ ckeditor.load(custom_url=url_for('static', filename='ckeditor/ckeditor.js')) }}
- {{ ckeditor.config(name='content') }}
- {% endblock content %}
- templates/other_page.html
Advertisement
Add Comment
Please, Sign In to add comment