Welcome to Django, a powerful Python web framework that simplifies the process of building dynamic websites. Let's dive into the world of Django together!
Django offers several advantages:
To install Django, use pip, the Python package manager:
pip install djangoCreate a new Django project using the following command:
django-admin startproject my_first_projectChange to the newly created project directory:
cd my_first_projectCreate a new Django app within the project:
python manage.py startapp my_first_appNow, let's write our first view!
Views in Django handle the logic of what to display in a web page. To create a simple view, edit the views.py file in your app directory:
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to my_first_app!")Now, let's make this view accessible.
Edit the urls.py file in your app directory to include the view:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]Now, run your server:
python manage.py runserverVisit http://127.0.0.1:8000/ in your browser, and you should see the message "Welcome to my_first_app!"
What does Django use for handling the logic of what to display in a web page?
Models in Django represent database tables and their fields. To create a simple model, edit the models.py file in your app directory:
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()Let's create a database migration and apply it:
python manage.py makemigrations
python manage.py migrateNow, let's create a view to display and manipulate the data.
In Django, what do models represent?
You've taken your first steps in the world of Django! By understanding views, URL patterns, and models, you've laid a solid foundation for your web development journey.
In the next lesson, we'll dive deeper into Django templates and forms, making our web applications more interactive and user-friendly. Stay tuned! π―