Master Django Basics: From Project Setup to Forms and Templates
This comprehensive guide introduces Django, outlines its key features, explains the standard project structure, walks through essential commands, demonstrates view and URL configuration, covers template syntax and tags, and details model creation, database operations, and form handling with both GET and POST methods.
Django Introduction
Django is a popular open‑source web application framework written in Python that follows the MVC (Model‑View‑Controller) design pattern.
Key Features of Django
Powerful ORM: define models as Python classes and perform database operations with minimal code.
Built‑in admin interface for easy content management.
Clean URL routing using regular expressions.
Extensible template system separating logic from presentation.
Integrated caching support (e.g., Memcached) for faster response.
Full internationalization and localization support.
Typical Django Project Layout
urls.py: URL entry point mapping URLs to view functions or classes. views.py: Handles requests, renders templates, and returns responses. models.py: Defines data models and interacts with the database. forms.py: Manages form rendering and validation (optional). templates/: Stores HTML templates rendered by views. admin.py: Configures the automatic admin site. settings.py: Project configuration (debug mode, static files, etc.).
Basic Django Commands
Create a project: django-admin startproject project-name Create an app: python manage.py startapp app-name (or django-admin startapp app-name).
Run the development server: python manage.py runserver 0.0.0.0:8000 (or simply python manage.py runserver).
Views and URL Configuration
from django.http import HttpResponse
def helloWorld(request):
return HttpResponse("Hello world! ") from django.conf.urls import url
from . import view
urlpatterns = [
url(r'^$', view.helloWorld),
]Access the view at http://127.0.0.1:8000/ or /helloWorld after updating the URL pattern.
Django Template System
Example template helloWorld.html: <h1>{{ helloWorld }}</h1> Configure template directories in settings.py (add BASE_DIR + "/templates" to TEMPLATES['DIRS']).
from django.shortcuts import render
def hello(request):
context = {'helloWorld': 'Hello World!'}
return render(request, 'helloWorld.html', context)Template tags include {% if %}, {% for %}, {% include %}, filters (e.g., {{ name|lower }}), and comments {# comment #}.
Models and Database Operations
Define a model in models.py:
from django.db import models
class Test(models.Model):
name = models.CharField(max_length=20)Configure the database in settings.py (example for MySQL):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'test',
'PASSWORD': 'test123',
'HOST': 'localhost',
'PORT': '3306',
}
}Run migrations:
python manage.py migrate
python manage.py makemigrations TestModel
python manage.py migrate TestModelBasic CRUD examples:
# Create
test = Test(name='Alice')
test.save()
# Read
list = Test.objects.all()
for obj in list:
print(obj.name)
# Update
test = Test.objects.get(id=1)
test.name = 'Alice'
test.save()
# Delete
test = Test.objects.get(id=1)
test.delete()Form Handling (GET and POST)
GET form example ( search_form.html) and view:
def search_form(request):
return render(request, 'search_form.html')
def search(request):
if 'q' in request.GET:
message = '搜索的内容为: ' + request.GET['q']
else:
message = '提交了空表单'
return HttpResponse(message) <form action="/search" method="get">
<input type="text" name="q">
<input type="submit" value="搜索">
</form>POST form example ( post.html) with CSRF token and view:
def search_post(request):
ctx = {}
if request.POST:
ctx['rlt'] = request.POST['q']
return render(request, 'post.html', ctx) <form action="/search-post" method="post">
{% csrf_token %}
<input type="text" name="q">
<input type="submit" value="搜索">
</form>
<p>{{ rlt }}</p>Update urls.py to include the new routes for the forms and database view.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
