Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Coined as “the web framework for perfectionists with deadlines”, Django facilitates the creation of complex, database-driven websites with ease.
Installation is straightforward using pip:
pip install django
To start a new project:
django-admin startproject projectname
A Django project comprises various apps (modules). Here’s a basic breakdown:
Let’s create a basic web page using Django.
First, create a new app:
python manage.py startapp myapp
Models (models.py
):
from django.db import models
class Greeting(models.Model):
text = models.CharField(max_length=200)
Views (views.py
):
from django.http import HttpResponse
from .models import Greeting
def hello(request):
greeting = Greeting(text="Hello, Django World!")
return HttpResponse(greeting.text)
URLs (urls.py
in your project directory):
from django.urls import path
from .views import hello
urlpatterns = [
path('hello/', hello, name='hello'),
]
After setting up your database and running migrations, visiting /hello/
should display “Hello, Django World!”.
Once you’ve set up your models, you can easily integrate them with Django’s built-in admin site. First, you’ll need to create a superuser:
python manage.py createsuperuser
Then, in the admin.py
of your app, you can register your models:
from django.contrib import admin
from .models import Greeting
admin.site.register(Greeting)
Now, by navigating to /admin/
, you can manage your Greeting
model instances through a user-friendly GUI.
Django’s ecosystem is vast. There’s a lot to explore, such as:
Conclusion:
Django is a robust and versatile framework that’s well-suited for developers looking to build web applications without reinventing the wheel. Its modularity and wide array of built-in tools make it an excellent choice for both beginners and seasoned developers. Whether you’re building a blog, an e-commerce platform, or a social media site, Django provides the structure and tools to get you started efficiently.