⚡ IS231 · Lecture 06 · Dr. Mohamed Nour Eldien · أسئلة امتحانات 2021 – 2025

Django —
Apps, URLs & Views

إزاي Django بيخدم صفحات حقيقية؟ شرح شامل لإنشاء الـ Apps، تسجيلها، بناء الـ URL Routing، كتابة الـ Views، وإرجاع الـ Responses — الشرح بالعربي والمصطلحات بالإنجليزي 🇪🇬

7
أقسام رئيسية
10+
سؤال امتحان حقيقي
2021–2025
سنوات الامتحانات
نجاح 🎯
01

Project vs App — الفرق بين المشروع والتطبيق

فكّر في الـ Project كالجامعة كاملها، والـ App كـ كلية واحدة جوّاها

🏛️ تمثيل حقيقي — University Analogy
🎓
Django Project
= الجامعة كلها
الـ Settings العامة، الـ Database، الـ Server Configuration
🏢
Django App
= كلية / قسم واحد
students app, courses app, library app
🗺️
URLs
= اللافتات الدالّة
/students/ /courses/

📁 Django Project

  • الإعدادات العامة للـ Server (settings.py)
  • ملف الـ URLs الرئيسي (urls.py)
  • يحتوي على عدة Apps مختلفة
  • بيُنشأ بأمر: django-admin startproject
  • Configuration واحدة للكل

📦 Django App

  • وحدة قائمة بذاتها مسؤولة عن Feature معين
  • ليها Views, URLs, Models, Templates خاصة بيها
  • ممكن تتعاد استخدام في Project تاني (Reusable)
  • بتُنشأ بأمر: python manage.py startapp
  • أمثلة: students, courses, accounts, library
💡 قاعدة: المشروع الواحد ممكن يضم عشرات الـ Apps. كل App بتتكلم في "قسم" واحد من الموقع وده بيخلي الكود أسهل في القراءة والصيانة والتطوير.
02

Creating & Setting Up a Django App — إنشاء وإعداد App

الخطوات من الأمر للتسجيل للشغل

⌨️ أمر إنشاء الـ App
TERMINAL
python manage.py startapp students

الأمر ده بيعمل مجلد جديد اسمه students جوّاه ملفات جاهزة تلقائياً.

📁 الملفات اللي Django بيعملها تلقائياً
students/ ├── views.py ← هنا بتكتب الـ Views (الـ Logic) ├── models.py ← بنية قاعدة البيانات (Database Structure) ├── admin.py ← تسجيل الـ Models في الـ Admin Panel ├── apps.py ← Class إعداد الـ App ├── tests.py ← الاختبارات التلقائية ├── __init__.py ← بيحوّل المجلد لـ Python Package └── migrations/ ← سجل التغييرات على قاعدة البيانات
⚠️ ملف مش موجود تلقائياً! ملف urls.py داخل الـ App مش بيتعمل تلقائياً — لازم تعمله إنت بنفسك وتكتب فيه الـ URL Patterns بتاعة الـ App.
🔑 دور كل ملف — مهم للامتحان
الملفدورهحالة استخدامه
views.pyتعريف الـ View Functionsمهم جداً
models.pyتعريف جداول قاعدة البياناتمهم جداً
admin.pyتسجيل الـ Models في الـ Admin Panelمهم
apps.pyConfiguration class للـ Appمتوسط
urls.pyURL Patterns خاصة بالـ App (يتعمل يدوياً)مهم جداً
migrations/سجل تغييرات الـ Databaseمهم
03

تسجيل الـ App في settings.py — INSTALLED_APPS

بدون التسجيل، Django مش بيعرف إن الـ App موجودة أصلاً

⚙️ خطوة إلزامية بعد كل app تنشئها
settings.py — INSTALLED_APPS
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'students',   # ← الـ App اللي أنشأناها
]
🚨 غلطة شائعة جداً: لو نسيت تضيف الـ App لـ INSTALLED_APPS، الـ Templates مش هتتاكتشف، والـ Models مش هتشتغل، والـ Admin مش هيشوفها. دايماً سجّل الـ App فور ما تعملها!
📊 ماذا يحدث لو لم تسجّل الـ App؟ — مشاكل شائعة
المشكلةالسبب
Templates غير موجودة في الـ DiscoveryDjango مش بيفتش جوّا الـ App عشان مش عارف بيها
Admin مش بيشوف الـ ModelsAdmin Registration بيحتاج App مسجّلة أولاً
Migrations مش بتشتغل صحالـ App نفسها مش معروفة
04

URL Dispatcher — كيف الـ Request يوصل للـ View

الرحلة الكاملة من المتصفح للكود Python

🗺️ ما هو الـ URL Dispatcher؟

الـ URL Dispatcher هو الـ Component اللي بيمبّط أي URL قادم على الـ Server لـ View Function معينة. بيقرأ الـ URL، بيقارنه بالـ URL Patterns المعرّفة، ولو لقى Match بيودّي الـ Request للـ View المناسبة.

🌐
Browser
HTTP Request
URL
📋
Project urls.py
Main Router
include()
📄
App urls.py
App Router
path()
⚙️
View Function
Python Code
Response
HTTP Response
HTML / JSON
💡 قاعدة: لو ما فيش Pattern بيطابق الـ URL، Django تلقائياً بيرجع 404 Not Found. الـ Pattern Matching بيتم من فوق لتحت (Top to Bottom) — أول Match بيفوز.
05

Project URLs & App URLs — مستويات الـ Routing

ليه في مستويين؟ وإيه الفرق؟

📂 Project-Level URLs — urls.py الرئيسي

ملف urls.py الرئيسي في مجلد الـ Project هو نقطة الدخول لكل الـ Requests. بيعمل حاجتين:

  • بيضيف مسار الـ Admin Panel
  • بيحوّل الـ Requests للـ Apps المختلفة باستخدام include()
myproject/urls.py — Project Level
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('students/', include('students.urls')),  # ← يحوّل كل /students/* للـ App
    path('courses/', include('courses.urls')),   # ← يحوّل كل /courses/* للـ App
]
💡 ليه include()؟
  • ملف الـ Project يفضل قصير وبسيط — مش هيحمل كل URLs الموقع
  • كل App بتتولى الـ URLs الداخلية بتاعتها
  • Apps جديدة ممكن تتضاف بسطر واحد بس
  • Debugging أسهل بكتير
📄 App-Level URLs — students/urls.py

الملف ده بتعمله إنت يدوياً جوّا مجلد الـ App. بيحدد الـ URLs الداخلية للـ App وكل واحدة بتوصّل لإنهي View.

students/urls.py — App Level
from django.urls import path
from . import views   # ← import الـ views من نفس المجلد

urlpatterns = [
    path('', views.home, name='home'),            # /students/
    path('about/', views.about, name='about'),    # /students/about/
    path('contact/', views.contact, name='contact'), # /students/contact/
]
💡 path() — المعاملات الثلاثة:
  • الأول: الـ Route String — المسار مثل 'about/'
  • الثاني: الـ View Function — مثل views.about
  • الثالث (اختياري): name= — اسم للـ URL للاستخدام في الـ Templates لاحقاً
📊 حساب الـ Full URL — كيف؟

الـ Full URL = الـ Prefix من Project urls + الـ Path من App urls

Project PrefixApp Pathالـ Full URL
students/'' (فاضي)/students/
students/about//students/about/
students/contact//students/contact/
courses/list//courses/list/
⚠️ Trailing Slash مهم: Django عارف يتعامل مع الـ Trailing Slash (/ في النهاية). خلّي أسلوبك ثابت في المشروع كله — إما بنهاية slash أو بدونها.
⚠️ ترتيب الـ URL Patterns مهم!
  • Django بيفحص الـ Patterns من فوق لتحت — أول Match يفوز
  • حط الـ Patterns الأكثر تحديداً (Specific) قبل الـ Broad ones
  • الـ Pattern العام (catch-all) لازم يكون آخر حاجة
CORRECT ORDER — الترتيب الصح
urlpatterns = [
    path('student/<int:id>/', views.student_detail),  # أكثر تحديداً — أول
    path('student/', views.students_list),           # أقل تحديداً — تاني
    path('', views.home),                             # Catch-all — آخر
]
06

Dynamic URL Parameters — قيم متغيرة في الـ URL

إزاي تمرّر قيم مثل ID أو اسم في الـ URL للـ View

🔀 URL Parameters — كيف تعرّفها

ممكن تضمّن قيم متغيرة في الـ URL Pattern باستخدام <type:name> — وDE القيمة بتوصل للـ View كـ Argument تلقائياً.

students/urls.py — Dynamic Parameter
urlpatterns = [
    path('student/<int:id>/', views.student_detail),  # id رقم صحيح
    path('profile/<str:username>/', views.profile),  # username نص
]
students/views.py — Receiving the Parameter
from django.http import HttpResponse

def student_detail(request, id):   # id بييجي كـ Argument
    return HttpResponse(f'طالب رقم: {id}')

def profile(request, username):
    return HttpResponse(f'Profile of: {username}')
🔠 Path Converters — أنواع الـ Parameters
الـ Converterالنوعمثال
<str:name>نص بدون Slash/students/ali/
<int:id>رقم صحيح فقط/students/42/
<slug:code>حروف وأرقام وـ Hyphen وـ Underscore/course/web-tech/
<uuid:item_id>UUID بالصيغة الكاملة/item/550e8400.../
07

Function-Based Views — الـ FBV

الـ View هي نقطة دخول الـ Business Logic — هنا بيتخذ القرار

⚙️ ما هو الـ View؟

الـ View في Django هو function Python عادي بيستقبل request object ولازم يرجع response object. ده بالظبط أول سطر في أي View تكتبه.

الـ View بيعمل:

  • بيقرأ الـ Request (Method, Headers, Data)
  • بيعمل الـ Business Logic والـ Validation
  • ممكن يجيب بيانات من الـ Database
  • بيختار نوع الـ Response
  • بيرجع الـ Response للمتصفح

الـ View مش بيعمل:

  • مش بيشتغل على الـ HTML مباشرة (للـ Template)
  • مش بيتعامل مع الـ Routing (للـ urls.py)
  • مش بيحفظ البيانات مباشرة (للـ Model)
📝 أنواع الـ Responses من الـ View
views.py — HttpResponse بسيطة
from django.http import HttpResponse

def home(request):
    return HttpResponse('Welcome to the Students App')

def about(request):
    return HttpResponse('This is the About page')

def contact(request):
    return HttpResponse('<h1>Contact Us</h1><p>Email: info@cu.edu.eg</p>')
⚠️ HttpResponse مع HTML مباشرة: ممكن لكن مش الأفضل! لو الصفحة كبيرة، الكود هيبقى فوضى. الأحسن استخدام render() مع Templates.
🧠 مثال كامل — 3 Views مع URLs
students/views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse('Students Home Page')

def contact(request):
    return HttpResponse('Contact the students office')

def help_page(request):
    return HttpResponse('Help and FAQ page')
students/urls.py — URL Mapping
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('contact/', views.contact, name='contact'),
    path('help/', views.help_page, name='help'),
]
💡 اللي بيحصل:
  • المتصفح يفتح /students/ → يشتغل home()
  • المتصفح يفتح /students/contact/ → يشتغل contact()
  • المتصفح يفتح /students/help/ → يشتغل help_page()
  • أي URL تاني → 404 Not Found
08

render() والـ Templates — الطريقة الصح

Separation of Concerns — الـ Logic هنا والـ HTML هناك

🎨 render() بدلاً من HttpResponse مباشرة

الـ render() هي الدالة المفضّلة لإرجاع HTML. بتاخد الـ request والـ Template ومتغيرات (Context) وبترجعها كـ HttpResponse.

views.py — render() مع Context
from django.shortcuts import render

def home(request):
    context = {
        'title': 'Students Home',
        'message': 'Welcome to the students portal',
        'count': 250,
    }
    return render(request, 'students/home.html', context)
📁 مكان الـ Templates

الـ Template Convention الموصى بيها في Django:

students/ └── templates/ └── students/ ← نفس اسم الـ App (مهم!) ├── home.html ├── about.html └── contact.html
⚠️ ليه نفس اسم الـ App في المسار؟ عشان لو عندك App تانية اسمها courses وعندها home.html كمان، Django هيتلخبط. بالاسم الكامل students/home.html مفيش لبس.
🖥️ Template Example — home.html
students/templates/students/home.html
<h1>{{ title }}</h1>
<p>{{ message }}</p>
<p>Total students: {{ count }}</p>

<!-- Template Tags — Logic -->
{% if count > 100 %}
  <span>Large class!</span>
{% endif %}
💡 Django Template Syntax — مهم جداً:
  • {{ variable }} — عرض قيمة متغير (Variable Output)
  • {% tag %} — Template Tags — Logic (for loops, if conditions, blocks)
  • {# comment #} — تعليق لا يظهر في الـ HTML
🔄 الرحلة الكاملة من URL لـ HTML
1
المستخدم يفتح /students/
المتصفح بيبعت HTTP GET Request للسيرفر
2
Project urls.py يرسله للـ App
include('students.urls') بيحوّل الـ Request لـ students/urls.py
3
App urls.py يطابق الـ Pattern
path('', views.home) تطابق، يُستدعى home(request)
4
View تُنفّذ وتُبني الـ Context
الـ View بتجيب البيانات وبتجهّز الـ Context Dictionary
5
render() يدمج الـ Template مع الـ Context
بيحوّل {{ title }} وغيرها للقيم الحقيقية
6
المتصفح يستقبل ويعرض HTML
الصفحة تظهر للمستخدم — الرحلة انتهت!
09

JsonResponse — ردود الـ API

لما بتعمل API بدل صفحة HTML

🔌 JsonResponse

ممكن الـ View ترجع JSON Data بدل HTML — مفيد جداً لعمل APIs. الـ JsonResponse بتحوّل الـ Python Dictionary لـ JSON تلقائياً وبتضيف الـ Content-Type الصح.

views.py — JsonResponse
from django.http import JsonResponse

def api_status(request):
    return JsonResponse({
        'status': 'ok',
        'app': 'students',
        'version': '1.0'
    })
views.py — View بتختار: HTML أم JSON؟
from django.http import HttpResponse, JsonResponse

def demo(request):
    if request.GET.get('format') == 'json':
        return JsonResponse({'page': 'demo'})
    return HttpResponse('Demo page in HTML')
10

Debugging & Common Errors — أخطاء شائعة وحلولها

اقرأ الـ Error Messages ببطء بدل الهلع!

🔴 404 Not Found
  • افحص الـ Full URL اللي بتكتبه في المتصفح
  • افحص إن Project urls فيها include('app.urls')
  • افحص إن App urls فيها الـ Pattern الصح
  • انتبه للـ Trailing Slash
  • افحص إن الـ App مسجّلة في INSTALLED_APPS
🟡 Import Errors
  • افحص اسم الـ File والـ Function بدقة
  • تأكد إن from . import views صح في الـ App urls
  • تأكد إن الـ Function موجودة فعلاً في views.py
  • اقرأ الـ Traceback بالكامل — الأخطاء بتدلك على السطر
🔧 أخطاء شائعة وحلولها
❌ خطأ — Missing include import
# خطأ
from django.urls import path

# صح
from django.urls import path, include
❌ خطأ — Wrong View Reference
# خطأ — view بدون s
path('about/', view.about)

# صح
path('about/', views.about)
❌ خطأ — Wrong App Name in include()
# خطأ — اسم الـ App غلط
path('students/', include('student.urls'))  # مفيش s في النهاية

# صح
path('students/', include('students.urls'))
🎯

أسئلة امتحانات Django Apps & URLs & Views

كل الأسئلة من امتحانات 2021 + 2024 + 2025 المتعلقة بالمحاضرة دي — مرتبة حسب ترتيب الشرح 🇪🇬

Q1 Final 2024 — Q.1
Django is based on which framework pattern?
A
MVC (Model-View-Controller)
B
MVVM (Model-View-ViewModel)
C
MVT (Model-View-Template)
D
None of the previous
✅ الإجابة الصح: C — MVT (Model View Template)
Django بيستخدم نمط الـ MVT:
  • Model: بنية البيانات والتعامل مع الـ Database
  • View: الـ Business Logic واستقبال الـ Requests
  • Template: الـ HTML وطريقة عرض البيانات
ملحوظة: الـ MVT يشبه الـ MVC لكن Django بيسمّي الـ Controller = View والـ View = Template.
Q2 Final 2024 — Q.2 | Final 2025 — T/F Q.8
For a model to be visible in the admin interface, it has to be registered in which file?
A
settings.py
B
admin.py (using admin.site.register(Model_name))
C
views.py
D
None of the previous
✅ الإجابة الصح: B — admin.py
عشان يظهر الـ Model في الـ Admin Interface على /admin/، لازم تعمل حاجتين:
  • import الـ Model في admin.py
  • استدعاء admin.site.register(Student)
from django.contrib import admin from .models import Student admin.site.register(Student)
Q3 Final 2025 — T/F Q.30
Django comes with a built-in user interface that allows you to administrate your data. To create the admin user, you write: python manage.py createuser. (True or False?)
A
True
B
False
✅ الإجابة الصح: B — False
الأمر الصح هو python manage.py createsuperuser وليس createuser! createsuperuser هو اللي بيعمل Admin User عنده صلاحية الدخول لـ /admin/. createuser مش موجود في Django.
Q4 Final 2024 — Q.5
What is the correct syntax for creating a Django project?
A
django start my_tennis_club
B
py manage.py start-django my_tennis_club
C
django-admin startproject my_tennis_club
D
None of the previous
✅ الإجابة الصح: C — django-admin startproject my_tennis_club
ده الأمر الرسمي لإنشاء Django Project جديد. بيعمل مجلد بيحتوي على settings.py، urls.py، manage.py وغيرها تلقائياً. مقارنة: startapp لإنشاء App، startproject لإنشاء Project.
Q5 Final 2024 — Q.6
If you have a Django application named members, and a model named Member, what is the correct syntax to import the model?
A
from members.models import Member
B
import Member from members
C
import members.Member
D
None of the previous
✅ الإجابة الصح: A — from members.models import Member
الـ Models في Django بتكون في ملف models.py جوّا مجلد الـ App. لاستيراد Model معين بتكتب: from app_name.models import ModelName. الصيغة بتتبع نمط Python القياسي.
Q6 Final 2024 — Q.4
To perform programming logic in Django templates, you can use 'template tags'. What is the correct syntax to start a for loop?
A
(for x in y)
B
<% for x in y %>
C
{% for x in y %}
D
None of the previous
✅ الإجابة الصح: C — {% for x in y %}
في Django Templates، الـ Template Tags (اللي بتعمل Logic زي loops وـ if conditions) بتُحاط بـ {% %}. مقارنة:
  • {% for x in y %} — Template Tag للـ Logic
  • {{ variable }} — عرض قيمة متغير
  • {# comment #} — تعليق مخفي
Q7 Final 2024 — Q.10
When you have done changes in a model in Django, which command has to be executed in order to make the changes take effect in the database?
A
python manage.py runmigrations
B
python manage.py executemigrations
C
python manage.py makemigrations
D
None of the previous
✅ الإجابة الصح: D — None of the previous
الأمر اللي بيخلي التغييرات تتنفذ فعلياً في الـ Database هو python manage.py migrate وهو مش موجود في الاختيارات. makemigrations بيجهّز ملف الترحيل بس.
🇪🇬 makemigrations = خطوة 1 (بيجهّز). migrate = خطوة 2 (بيطبّق في الـ DB).
Q8 Final 2025 — T/F Q.11
"migrate" command in Django is used to show the changes happened in the database. (True or False?)
A
True
B
False
✅ الإجابة الصح: B — False
الأمر migrate مش بيعرض التغييرات — ده بيعمل تطبيق التغييرات على الـ Database الفعلي (Creates/Alters Tables). اللي بيعرض التغييرات ويعمل migration file هو makemigrations.
Q9 Final 2025 — T/F Q.5
Django views represents the presentation layer of Django. (True or False?)
A
True
B
False
✅ الإجابة الصح: B — False
الـ View في Django مش بتمثّل الـ Presentation Layer — ده الـ Template! الـ View بتمثّل الـ Business Logic Layer. الـ Template هي اللي بتتحكم في طريقة عرض البيانات (Presentation). في الـ MVT:
  • Model = Data Layer
  • View = Business Logic
  • Template = Presentation Layer
Q10 Final 2025 — T/F Q.9
Post.Objects.all() will retrieve all objects in the Post table. (True or False?)
A
True
B
False
✅ الإجابة الصح: B — False
الكود ده غلط! الـ Objects بـ O كبيرة غلط. الصح هو Post.objects.all() بـ o صغيرة. Python وDjango Case-Sensitive — objects (كلها صغيرة) هو الـ Manager الافتراضي، أما Objects بـ O كبيرة فمش موجود وهيطلع AttributeError.
Q11 Mini Quiz — Lecture 6
Which file usually contains the line include("students.urls")?
A
students/views.py
B
Project urls.py (Main)
C
students/models.py
D
settings.py
✅ الإجابة الصح: B — Project urls.py
الـ include() بيتكتب في ملف الـ Project urls.py الرئيسي (مش App urls). بيقول للـ Django: "أي Request بييجي على /students/*، حوّله لملف students/urls.py عشان يكمّل الـ Routing جوّاه."
Q12 Mini Quiz — Lecture 6
If project urls route students/ to students.urls, and app urls contain path("about/", views.about), what is the full browser path?
A
/about/
B
/students/about/
C
/students/
D
/about/students/
✅ الإجابة الصح: B — /students/about/
الـ Full URL = Project Prefix + App Path
= students/ + about/ = /students/about/
ده بالظبط إزاي Django بيركّب الـ URLs عبر المستويين.