Tutorial: Creating a Diary App with Flask

Posted by


In this Flask tutorial, we will create a diary web application. This application will allow users to log in, create diary entries, view their diary entries, edit and delete them.

Step 1: Installing Flask
First, make sure you have Python installed on your machine. You can check by running the following command in your terminal:

python --version

If you don’t have Python installed, you can download it from the official Python website. Once you have Python installed, you can install Flask using pip, the Python package manager. Run the following command in your terminal:

pip install Flask

Step 2: Setting up the project structure
Create a new directory for your Flask project. Inside this directory, create a new file called app.py. This will be the main file for our Flask application. Create another directory called templates inside the project directory. This directory will contain all the HTML templates for our application.

Step 3: Setting up the Flask application
Open the app.py file and add the following code:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
  return render_template('index.html')

if __name__ == '__main__':
  app.run()

This code sets up a basic Flask application with a single route that renders an index.html template.

Step 4: Creating the HTML templates
Inside the templates directory, create a new file called index.html. Add the following code to the index.html file:

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Diary</title>
  </head>
  <body>
    <h1>Welcome to the Flask Diary App!</h1>
  </body>
</html>

Step 5: Running the Flask application
To run your Flask application, navigate to the project directory in your terminal and run the following command:

python app.py

You should see a message in your terminal saying that the Flask application is running. Open a web browser and navigate to http://127.0.0.1:5000/ to see your Flask application in action.

Step 6: Creating the Diary functionality
Now that we have the basic Flask application set up, let’s add the functionality to create, view, edit, and delete diary entries.

First, we need to create a database to store the diary entries. For simplicity, we will use SQLite as the database for this tutorial. To use SQLite with Flask, you will need to install the Flask-SQLAlchemy package:

pip install Flask-SQLAlchemy

Next, add the following code to your app.py file to set up the SQLite database:

from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///diary.db'
db = SQLAlchemy(app)

class DiaryEntry(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  title = db.Column(db.String(100), nullable=False)
  content = db.Column(db.Text, nullable=False)

db.create_all()

This code defines a DiaryEntry model with id, title, and content fields. The db.create_all() method creates the SQLite database with the DiaryEntry table.

Step 7: Implementing the CRUD functionality
Now, let’s implement the CRUD functionality for the diary entries.

Add the following routes to your app.py file:

from flask import request, redirect, url_for

@app.route('/add_entry', methods=['POST'])
def add_entry():
  title = request.form['title']
  content = request.form['content']
  new_entry = DiaryEntry(title=title, content=content)
  db.session.add(new_entry)
  db.session.commit()
  return redirect(url_for('index'))

@app.route('/edit_entry/<int:entry_id>', methods=['GET', 'POST'])
def edit_entry(entry_id):
  entry = DiaryEntry.query.get(entry_id)
  if request.method == 'POST':
    entry.title = request.form['title']
    entry.content = request.form['content']
    db.session.commit()
    return redirect(url_for('index'))
  return render_template('edit_entry.html', entry=entry)

@app.route('/delete_entry/<int:entry_id>')
def delete_entry(entry_id):
  entry = DiaryEntry.query.get(entry_id)
  db.session.delete(entry)
  db.session.commit()
  return redirect(url_for('index'))

These routes handle adding, editing, and deleting diary entries. The add_entry route creates a new diary entry, the edit_entry route allows users to edit existing entries, and the delete_entry route deletes entries.

Step 8: Updating the templates
Update the index.html template to display a list of diary entries and add links to create, edit, and delete entries:

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Diary</title>
  </head>
  <body>
    <h1>Welcome to the Flask Diary App!</h1>

    <a href="/add_entry">Add New Entry</a>

    <ul>
      {% for entry in entries %}
      <li>
        <h2>{{ entry.title }}</h2>
        <p>{{ entry.content }}</p>
        <a href="/edit_entry/{{ entry.id }}">Edit</a>
        <a href="/delete_entry/{{ entry.id }}">Delete</a>
      </li>
      {% endfor %}
    </ul>
  </body>
</html>

Create a new file called add_entry.html inside the templates directory and add the following code:

<!DOCTYPE html>
<html>
  <head>
    <title>Add New Entry</title>
  </head>
  <body>
    <h1>Add New Entry</h1>

    <form method="post" action="/add_entry">
      <label for="title">Title</label>
      <input type="text" name="title" id="title">

      <label for="content">Content</label>
      <textarea name="content" id="content"></textarea>

      <button type="submit">Save</button>
    </form>
  </body>
</html>

Create a new file called edit_entry.html inside the templates directory and add the following code:

<!DOCTYPE html>
<html>
  <head>
    <title>Edit Entry</title>
  </head>
  <body>
    <h1>Edit Entry</h1>

    <form method="post" action="/edit_entry/{{ entry.id }}">
      <label for="title">Title</label>
      <input type="text" name="title" id="title" value="{{ entry.title }}">

      <label for="content">Content</label>
      <textarea name="content" id="content">{{ entry.content }}</textarea>

      <button type="submit">Save</button>
    </form>
  </body>
</html>

Step 9: Finalizing the application
Finally, update the index route in your app.py file to fetch all diary entries from the database and pass them to the index.html template:

@app.route('/')
def index():
  entries = DiaryEntry.query.all()
  return render_template('index.html', entries=entries)

Now you have a fully functional diary web application built using Flask. You can add, edit, and delete diary entries through the web interface.

This tutorial covered the basics of building a Flask application with CRUD functionality. You can further enhance the application by adding features like user authentication, date and time stamps for entries, search and filter functionality, and more.

I hope you found this Flask tutorial helpful and enjoyed building the diary application. Flask is a versatile and powerful framework that allows you to create web applications quickly and efficiently. Happy coding!

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x