For programmers who use Python's Django framework for web development, the following points must be understood.
Environment configuration and project initialization
Order:
pip install django
django-admin startproject myproject
Analysis:
- Install Django using pip.
django-admin startproject
Initialize a new Django project using
Create app
Order:
cd myproject
python manage.py startapp myapp
Analysis:
- Go into the project folder.
- Use to
python manage.py startapp
create a new application.
Database migration
Order:
python manage.py makemigrations
python manage.py migrate
Analysis:
makemigrations
A new migration file will be created.migrate
Practical application of these migrations to the database.
Start the development server
Order:
python manage.py runserver
Analysis:
Start the development server, usually on port 8000.
Create a super user (for background management)
Order:
python manage.py createsuperuser
Analysis:
Create a new super user to log in to Django's admin backend.
Django models (Models)
- Define data structures and database table mappings.
Code example:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Analysis:
A model named is created Book
with the fields title
and author
.
Django views (Views)
- Handle user requests and return responses.
Code example:
from django.http import HttpResponse
def hello_world(request):
return HttpResponse('Hello, world!')
Analysis:
Created a simple view that returns "Hello, world!"
Django templates (Templates)
- Used to dynamically generate HTML pages.
Code example:
<!DOCTYPE html>
<html>
<head>
<title>{
{ title }}</title>
</head>
<body>
<h1>{
{ header }}</h1>
</body>
</html>
Analysis:
A simple template that accepts the variables title
and header
to dynamically generate HTML.
Django forms (Forms)
- Used to handle user input.
Code example:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
Analysis:
Defines a ContactForm
form named containing the name
and email
fields.
Django Admin
- Used to create background management interface.
Code example:
from django.contrib import admin
from .models import Book
admin.site.register(Book)
Analysis:
Register Book
the model in the admin background, so that Book
CRUD operations on data can be performed in the background.
[Reminder] These are just some of the core concepts and operations in the Django framework. For a deeper understanding, it is recommended to study advanced topics such as user authentication, using middleware, caching, signals, and creating RESTful APIs.
User Authentication
Django comes with a powerful user authentication system.
Order:
python manage.py createsuperuser
Analysis:
This creates a superuser with access to the Django admin interface.
Code example:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
Analysis:
Use @login_required
a decorator to protect the view so that only logged-in users can access it.
Use middleware
Middleware is a hook that handles requests and responses.
Code example:
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
Analysis:
This is a very basic middleware example that does nothing but simply pass the request and response.
cache
Django supports multiple caching backends (e.g., memcached, redis).
Code example:
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def my_view(request):
...
Analysis:
@cache_page
The decorator will cache the output of the view, and the parameter is the number of seconds to cache (in this case, 15 minutes).
Signals
Signals are used to allow decoupled applications to be notified when certain events occur.
Code example:
from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import MyModel
@receiver(pre_save, sender=MyModel)
def my_callback(sender, **kwargs):
...
Analysis:
Here we use pre_save
a signal to MyModel
execute the function before being saved my_callback
.
Create a RESTful API
Django REST framework is a powerful library for quickly building RESTful APIs.
Order:
pip install djangorestframework
Code example:
from rest_framework import serializers, viewsets
from myapp.models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
Analysis:
MyModelSerializer
A serializer named is defined forMyModel
serializing instances of to JSON.- A view set named is defined
MyModelViewSet
to handle basic CRUD operations.
The above is only a basic introduction and simple examples of advanced topics. Each topic has many in-depth and advanced uses. If you are more interested in a certain topic, I recommend checking out Django's official documentation or related tutorials for in-depth study.