الدرس 2 من مشروع Flask Notes App : إضافة ملاحظات وحفظها في قاعدة البيانات

🎯 هدف الدرس

سنتعلم اليوم كيف نُنشئ نموذج (Form) لإضافة ملاحظات جديدة،
وكيف نحفظها في قاعدة بيانات باستخدام SQLite.

2 من مشروع Flask Notes App

⚙️ أولاً: إعداد قاعدة البيانات

ننشئ ملفًا جديدًا باسم database.py ليحتوي على كود إنشاء قاعدة البيانات:

import sqlite3

def init_db():
    conn = sqlite3.connect('notes.db')
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS notes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            content TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()
    print("تم إنشاء قاعدة البيانات بنجاح!")

if __name__ == "__main__":
    init_db()

📌 شغّل هذا الملف مرة واحدة فقط (باستخدام الأمر python database.py) لإنشاء قاعدة البيانات.


🧱 ثانيًا: تحديث ملف app.py

نضيف مسار لإضافة الملاحظات (/add) ومسار لعرض جميع الملاحظات (/notes):

from flask import Flask, render_template, request, redirect
import sqlite3

app = Flask(__name__)

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

@app.route('/add', methods=['GET', 'POST'])
def add_note():
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        
        conn = sqlite3.connect('notes.db')
        cursor = conn.cursor()
        cursor.execute('INSERT INTO notes (title, content) VALUES (?, ?)', (title, content))
        conn.commit()
        conn.close()
        return redirect('/notes')
    
    return render_template('add_note.html')

@app.route('/notes')
def show_notes():
    conn = sqlite3.connect('notes.db')
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM notes')
    notes = cursor.fetchall()
    conn.close()
    return render_template('notes.html', notes=notes)

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

🎨 ثالثًا: إنشاء صفحة إضافة الملاحظات

templates/add_note.html

{% extends 'base.html' %}
{% block content %}
<div class="container mt-5">
  <h2 class="text-primary text-center">إضافة ملاحظة جديدة</h2>
  <form method="POST" class="mt-4">
    <div class="mb-3">
      <label class="form-label">عنوان الملاحظة</label>
      <input type="text" name="title" class="form-control" required>
    </div>
    <div class="mb-3">
      <label class="form-label">محتوى الملاحظة</label>
      <textarea name="content" class="form-control" rows="4" required></textarea>
    </div>
    <button type="submit" class="btn btn-success w-100">حفظ الملاحظة</button>
  </form>
</div>
{% endblock %}

📋 رابعًا: إنشاء صفحة عرض الملاحظات

templates/notes.html

{% extends 'base.html' %}
{% block content %}
<div class="container mt-5">
  <h2 class="text-center text-primary mb-4">جميع الملاحظات</h2>
  {% if notes %}
    <div class="list-group">
      {% for note in notes %}
      <div class="list-group-item">
        <h5>{{ note[1] }}</h5>
        <p>{{ note[2] }}</p>
      </div>
      {% endfor %}
    </div>
  {% else %}
    <p class="text-center text-muted">لا توجد ملاحظات بعد.</p>
  {% endif %}
</div>
{% endblock %}

✅ نتيجة الدرس

الآن يمكنك:

  • الدخول إلى /add لإضافة ملاحظات جديدة
  • ثم الذهاب إلى /notes لعرضها كلها


🧠 تمرين الدرس الثاني

أضف زر “عودة إلى الصفحة الرئيسية” في كل من صفحتي إضافة الملاحظة و عرض الملاحظات بحيث يُعيد المستخدم إلى /.


🎯 الهدف من التمرين:

إنشاء نموذج (Form) لإضافة ملاحظة جديدة، ثم حفظها في قاعدة البيانات (SQLite).


🧠 المتطلبات:

قبل البدء تأكد أن ملفك الأساسي هو app.py، وأن قاعدة البيانات جاهزة.
إذا لم تكن موجودة، فأنشئ ملف قاعدة بيانات باسم notes.db.


📁 هيكل المشروع حتى الآن:

notes_app/
│
├── app.py
├── templates/
│   ├── base.html
│   └── index.html
│
└── static/
    └── style.css

🧩 الكود الكامل لملف app.py

from flask import Flask, render_template, request, redirect, url_for
import sqlite3

app = Flask(__name__)

# إنشاء جدول الملاحظات (مرة واحدة فقط)
def create_table():
    conn = sqlite3.connect('notes.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS notes (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    title TEXT NOT NULL,
                    content TEXT NOT NULL
                )''')
    conn.commit()
    conn.close()

create_table()

# الصفحة الرئيسية
@app.route('/')
def index():
    conn = sqlite3.connect('notes.db')
    c = conn.cursor()
    c.execute("SELECT * FROM notes")
    notes = c.fetchall()
    conn.close()
    return render_template('index.html', notes=notes)

# إضافة ملاحظة جديدة
@app.route('/add', methods=['POST'])
def add_note():
    title = request.form['title']
    content = request.form['content']

    conn = sqlite3.connect('notes.db')
    c = conn.cursor()
    c.execute("INSERT INTO notes (title, content) VALUES (?, ?)", (title, content))
    conn.commit()
    conn.close()

    return redirect(url_for('index'))

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

🖋 ملف القالب index.html

{% extends "base.html" %}
{% block content %}
<h2 class="title">📝 ملاحظاتك</h2>

<form action="/add" method="POST" class="note-form">
    <input type="text" name="title" placeholder="عنوان الملاحظة" required>
    <textarea name="content" placeholder="اكتب الملاحظة هنا..." required></textarea>
    <button type="submit">إضافة</button>
</form>

<div class="notes-container">
    {% for note in notes %}
        <div class="note-card">
            <h3>{{ note[1] }}</h3>
            <p>{{ note[2] }}</p>
        </div>
    {% else %}
        <p>لا توجد ملاحظات بعد 🌿</p>
    {% endfor %}
</div>
{% endblock %}

🧱 ملف base.html

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <title>تطبيق الملاحظات</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <div class="container">
        <h1>📔 تقنيات نور التعليمية</h1>
        {% block content %}{% endblock %}
    </div>
</body>
</html>

🎨 ملف style.css

body {
    font-family: "Tajawal", sans-serif;
    background: #f3f5f7;
    direction: rtl;
    margin: 0;
    padding: 0;
}

.container {
    width: 80%;
    margin: 40px auto;
    text-align: center;
}

.note-form {
    background: white;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.note-form input, .note-form textarea {
    width: 90%;
    padding: 10px;
    margin: 10px 0;
    border-radius: 8px;
    border: 1px solid #ccc;
}

.note-form button {
    background: #2e86de;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 8px;
    cursor: pointer;
    transition: background 0.3s;
}

.note-form button:hover {
    background: #1b4f72;
}

.notes-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
    gap: 20px;
    margin-top: 30px;
}

.note-card {
    background: white;
    padding: 15px;
    border-radius: 10px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

✅ النتيجة:

عند تشغيل التطبيق (python app.py)
ستظهر صفحة يمكن من خلالها:

  • كتابة عنوان الملاحظة ومحتواها
  • الضغط على "إضافة"
  • ليتم حفظها مباشرة في قاعدة البيانات وتظهر ضمن قائمة الملاحظات.

تعليقات