Guest User

Untitled

a guest
Dec 14th, 2025
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.67 KB | None | 0 0
  1.  
  2. app.py
  3.  
  4.  
  5. import os
  6. # flask imports
  7. from flask import Flask, flash, redirect, render_template, url_for
  8. from flask_sqlalchemy import SQLAlchemy
  9. from flask_ckeditor import CKEditor, CKEditorField
  10. # forms
  11. from flask_wtf import FlaskForm
  12. from sqlalchemy.orm import Mapped, mapped_column
  13. from wtforms import  SubmitField
  14. from wtforms.validators import DataRequired, ValidationError
  15.  
  16. basedir = os.path.abspath(os.path.dirname(__file__))
  17.  
  18. # 1. Initialize Extensions (No longer importing SQLAlchemy twice)
  19. db = SQLAlchemy()
  20. # create the app
  21. app = Flask(__name__)
  22. ckeditor = CKEditor(app)
  23.  
  24. # 2. Configuration
  25. app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
  26. app.config['SECRET_KEY']= 'secret_key'
  27. app.config["CKEDITOR_PKG_TYPE"] = 'full'
  28. app.config["CKEDITOR_EXTRA_PLUGINS"] = ['mathjax']
  29. # initialize the app with the extension
  30. db.init_app(app)
  31.  
  32.  
  33. # 3. Model Definition
  34. class Posts(db.Model):
  35.     id: Mapped[int] = mapped_column(primary_key=True)
  36.     # FIX: Use db.Text for CKEditor (long-form content)
  37.     content: Mapped[str] = mapped_column(db.Text)
  38.    
  39.     def __repr__(self):
  40.         # IMPROVEMENT: Safer __repr__ for long content
  41.         return f'<Post {self.id}: {self.content[:20]}...>'
  42.  
  43.  
  44.  
  45. # 5. Forms
  46. class CreatePostForm(FlaskForm):
  47.     # CKEditorField is correct for rich text input
  48.     content = CKEditorField('Content', validators=[DataRequired('Content is required')])
  49.     submit = SubmitField('Submit')
  50.  
  51.  
  52.  
  53.  
  54. # 6. Routes
  55.  
  56. @app.route('/', methods = ['GET', 'POST'])
  57. @app.route('/home', methods = ['GET', 'POST'])
  58. def home():
  59.     form = CreatePostForm()
  60.     if form.validate_on_submit():
  61.         content = form.content.data
  62.         add_postinfo = Posts(content=content)
  63.         db.session.add(add_postinfo)
  64.         db.session.commit()
  65.         flash('Post created successfully!', 'success')
  66.         return redirect(url_for('other_page')) # Redirect to the check page
  67.        
  68.     return render_template('home.html', title='Home', form=form)
  69.  
  70.  
  71. @app.route('/other_page', methods = ['GET', 'POST'])
  72. def other_page():
  73.  
  74.     all_posts = db.session.query(Posts).all()
  75.  
  76.     # You need to render a template here!
  77.     # Assuming you have an 'other_page.html' template
  78.     return render_template('other_page.html', title='Check Post', all_posts=all_posts )
  79.  
  80. # 7. Database Creation and App Run
  81. if __name__ == '__main__':
  82.     with app.app_context():
  83.         # Ensure tables are created before running the app
  84.         db.create_all()
  85.        
  86.     app.run(debug=True)
  87.  
  88.  
  89.  
  90. templates/layout.html
  91.  
  92. <!DOCTYPE html>
  93. <html lang="en">
  94. <head>
  95.     <meta charset="UTF-8">
  96.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  97.     <title>Document</title>
  98.    
  99.  
  100. </head>
  101. <body>
  102.     {% block content %}
  103.     {% endblock content %}
  104. </body>
  105. </html>
  106.  
  107.  
  108.  
  109.  
  110.  
  111.  
  112. templates/home.html
  113.  
  114.  
  115. {% extends "layout.html" %}
  116. <!-- get the error message from wtf forms -->
  117. {% from "_formhelpers.html" import render_field %}
  118. {% block title %}  {{title}}  {% endblock title %}
  119.  
  120. <!-- should I use block content or an different name?-->
  121. {% block content %}
  122.         <!-- Once you get the error message from ( "_formhelpers.html" import render_field) , you use novalidate to
  123.         get the error message from wtf forms and makes it show up on the screen. %} -->
  124.         <form action="" method="post" novalidate>
  125.                 <!-- Make the secret key work -->
  126.                 {{ form.csrf_token }}
  127.                 {{ form.content | safe }}
  128.  
  129.                 <input type="submit" value="Submit">
  130.         </form>
  131.  
  132.  
  133.         {{ ckeditor.load(custom_url=url_for('static', filename='ckeditor/ckeditor.js')) }}
  134.         {{ ckeditor.config(name='content') }}      
  135.        
  136.  
  137.  
  138. {% endblock content %}
  139.  
  140.  
  141.  
  142.  
  143. {% extends "layout.html" %}
  144.  
  145.  
  146. <!-- get the error message from wtf forms -->
  147. {% from "_formhelpers.html" import render_field %}
  148. {% block title %}  {{title}}  {% endblock title %}
  149.  
  150. <!-- should I use block content or an different name?-->
  151. {% block content %}
  152.         <!-- Once you get the error message from ( "_formhelpers.html" import render_field) , you use novalidate to
  153.         get the error message from wtf forms and makes it show up on the screen. %} -->
  154.         <form action="" method="post" novalidate>
  155.                 <!-- Make the secret key work -->
  156.                 {{ form.csrf_token }}
  157.                 {{ form.content | safe }}
  158.  
  159.                 <input type="submit" value="Submit">
  160.         </form>
  161.  
  162.  
  163.         {{ ckeditor.load(custom_url=url_for('static', filename='ckeditor/ckeditor.js')) }}
  164.         {{ ckeditor.config(name='content') }}      
  165.        
  166.  
  167.  
  168. {% endblock content %}
  169.  
  170.  
  171.  
  172.  
  173. templates/other_page.html
  174.  
  175.  
  176.  
Advertisement
Add Comment
Please, Sign In to add comment