Master Django Basics: From Project Setup to Models and Forms
This tutorial introduces Django, outlines its major features, explains the standard project directory, provides essential command‑line tools, demonstrates how to create views, URLs, templates, and models, and walks through database operations and both GET and POST form handling, all with clear code examples.
1. Introduction
Django is an open‑source web application framework written in Python that follows the MVC (model‑view‑controller) design pattern and powers many successful websites and apps.
2. Key Features
Powerful ORM: define database tables with Python classes and perform queries with a high‑level API, while still allowing raw SQL.
Built‑in admin interface: generate a full‑featured administration site with just a few lines of code.
Elegant URL routing: map URLs to view functions using regular expressions.
Extensible template system: separate HTML presentation from Python logic.
Cache integration: work with memcached or other back‑ends for faster response times.
Internationalization: full support for multiple languages and translations.
3. Project Layout
urls.py: URL entry point that links patterns to view functions or class‑based views. views.py: Handles requests, renders templates, and returns responses. models.py: Defines data models and interacts with the database. forms.py: Defines form fields, validation, and rendering (optional). templates/ folder: Stores HTML templates used by views. admin.py: Registers models for the automatic admin site. settings.py: Configuration file (DEBUG flag, static files, etc.).
4. Basic Commands
Start a new project: django-admin startproject project-name Create a new 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 (accessible from other machines) or python manage.py runserver (local only).
5. Views and URLs
Example view returning a simple string:
from django.http import HttpResponse
def helloWorld(request):
return HttpResponse("Hello world! ")Corresponding URL pattern:
from django.conf.urls import url
from . import view
urlpatterns = [
url(r'^$', view.helloWorld),
]After adding a path segment:
urlpatterns = [
url(r'^helloWorld$', view.helloWorld),
]Access the view at http://127.0.0.1:8000/helloWorld.
6. Templates
Place helloWorld.html in the app’s templates folder:
<h1>{{ helloWorld }}</h1>Tell Django where to look for templates by adding the directory to TEMPLATES['DIRS'] in settings.py:
TEMPLATES = [{
...
'DIRS': [BASE_DIR + "/templates",],
...
}]Render the template from a view:
from django.shortcuts import render
def hello(request):
context = {'helloWorld': 'Hello World!'}
return render(request, 'helloWorld.html', context)Template tags such as {% if %}, {% for %}, {% include %}, and filters like {{ name|lower }} are supported.
7. Models and Database
Example model using MySQL:
from django.db import models
class Test(models.Model):
name = models.CharField(max_length=20)Database configuration in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'test',
'PASSWORD': 'test123',
'HOST': 'localhost',
'PORT': '3306',
}
}Typical migration commands:
python manage.py makemigrations TestModel
python manage.py migrate TestModelBasic CRUD operations demonstrated with HttpResponse views that create, read, update, and delete Test objects.
8. Forms (GET and POST)
GET form example:
from django.http import HttpResponse
from django.shortcuts import render_to_response
def search_form(request):
return render_to_response('search_form.html')
def search(request):
request.encoding = 'utf-8'
if 'q' in request.GET:
message = '搜索的内容为: ' + request.GET['q']
else:
message = '提交了空表单'
return HttpResponse(message)Corresponding search_form.html contains a simple <form> with a text input named q.
POST form example (requires CSRF token):
from django.shortcuts import render
def search_post(request):
ctx = {}
if request.POST:
ctx['rlt'] = request.POST['q']
return render(request, 'post.html', ctx)URL patterns are extended to include the new view:
urlpatterns = [
url(r'^search-form$', search.search_form),
url(r'^search$', search.search),
url(r'^search-post$', search2.search_post),
]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.
