目录
Django简介
Django是一个高级的Python Web框架,它鼓励快速开发和干净、实用的设计。Django遵循”不要重复自己”(DRY)的原则,并使用”约定优于配置”的方法。
主要特点:
- 快速开发:Django的设计目标是让开发者能够快速构建Web应用
- 功能完整:内置用户认证、内容管理、站点地图等功能
- 安全性:帮助开发者避免常见的安全错误
- 可扩展:可以处理高流量的网站
环境准备
1. 安装Python
确保您的系统已安装Python 3.8或更高版本:
python --version2. 创建虚拟环境
# 创建虚拟环境
python -m venv mywebsite_env
# 激活虚拟环境
# Windows:
mywebsite_env\Scripts\activate
# macOS/Linux:
source mywebsite_env/bin/activate3. 安装Django
pip install django4. 验证安装
django-admin --version创建Django项目
1. 创建项目
django-admin startproject mywebsite
cd mywebsite2. 初始数据库迁移
python manage.py migrate项目结构详解
创建项目后,您会看到以下目录结构:
mywebsite/
manage.py
mywebsite/
__init__.py
settings.py
urls.py
wsgi.py
asgi.py
文件说明:
manage.py: Django项目管理脚本settings.py: 项目配置文件urls.py: 主URL配置文件wsgi.py: WSGI兼容的Web服务器入口点asgi.py: ASGI兼容的Web服务器入口点
创建应用
Django项目由多个应用组成。对于单主页网站,我们创建一个主应用:
python manage.py startapp home应用目录结构:
home/
__init__.py
admin.py
apps.py
migrations/
models.py
tests.py
views.py
注册应用
在 mywebsite/settings.py 中添加应用:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home', # 添加这一行
]编写视图函数
在 home/views.py 中创建视图:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
"""主页视图"""
context = {
'title': '欢迎来到我的网站',
'welcome_message': '这是使用Django构建的单主页网站',
'features': [
'简单易用',
'功能强大',
'安全可靠',
'可扩展性强'
]
}
return render(request, 'home/index.html', context)
def about(request):
"""关于页面视图"""
return render(request, 'home/about.html', {
'title': '关于我们'
})配置URL路由
1. 创建应用的URL配置
在 home/ 目录下创建 urls.py 文件:
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
]2. 配置主URL
编辑 mywebsite/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
]创建模板
1. 创建模板目录
mkdir -p home/templates/home2. 创建基础模板
创建 home/templates/home/base.html:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}我的网站{% endblock %}</title>
{% load static %}
<link rel="stylesheet" href="{% static 'home/css/style.css' %}">
</head>
<body>
<header>
<nav>
<div class="nav-container">
<h1><a href="{% url 'home:index' %}">我的网站</a></h1>
<ul>
<li><a href="{% url 'home:index' %}">首页</a></li>
<li><a href="{% url 'home:about' %}">关于</a></li>
</ul>
</div>
</nav>
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<p>© 2024 我的网站. 保留所有权利.</p>
</footer>
</body>
</html>3. 创建主页模板
创建 home/templates/home/index.html:
{% extends 'home/base.html' %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<div class="hero-section">
<h2>{{ welcome_message }}</h2>
<p>探索Django的强大功能</p>
</div>
<div class="features-section">
<h3>网站特点</h3>
<div class="features-grid">
{% for feature in features %}
<div class="feature-card">
<h4>{{ feature }}</h4>
<p>Django让Web开发变得更加{{ feature }}</p>
</div>
{% endfor %}
</div>
</div>
{% endblock %}4. 创建关于页面模板
创建 home/templates/home/about.html:
{% extends 'home/base.html' %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<div class="about-section">
<h2>关于我们</h2>
<p>这是一个使用Django框架构建的简单网站示例。</p>
<p>Django是一个高级的Python Web框架,能够快速开发安全和可维护的网站。</p>
<h3>技术栈</h3>
<ul>
<li>Python</li>
<li>Django</li>
<li>HTML5</li>
<li>CSS3</li>
<li>SQLite</li>
</ul>
</div>
{% endblock %}静态文件处理
1. 创建静态文件目录
mkdir -p home/static/home/css
mkdir -p home/static/home/js
mkdir -p home/static/home/images2. 创建CSS样式
创建 home/static/home/css/style.css:
/* 基础样式 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Arial', sans-serif;
line-height: 1.6;
color: #333;
background-color: #f4f4f4;
}
/* 导航栏样式 */
header {
background: #2c3e50;
color: white;
padding: 1rem 0;
position: fixed;
width: 100%;
top: 0;
z-index: 1000;
}
.nav-container {
max-width: 1200px;
margin: 0 auto;
padding: 0 2rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.nav-container h1 a {
color: white;
text-decoration: none;
}
.nav-container ul {
display: flex;
list-style: none;
}
.nav-container ul li {
margin-left: 2rem;
}
.nav-container ul li a {
color: white;
text-decoration: none;
transition: color 0.3s;
}
.nav-container ul li a:hover {
color: #3498db;
}
/* 主要内容样式 */
main {
margin-top: 80px;
min-height: calc(100vh - 160px);
padding: 2rem 0;
}
.hero-section {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
text-align: center;
padding: 4rem 2rem;
}
.hero-section h2 {
font-size: 2.5rem;
margin-bottom: 1rem;
}
.hero-section p {
font-size: 1.2rem;
}
.features-section {
max-width: 1200px;
margin: 3rem auto;
padding: 0 2rem;
}
.features-section h3 {
text-align: center;
margin-bottom: 2rem;
color: #2c3e50;
}
.features-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 2rem;
margin-top: 2rem;
}
.feature-card {
background: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
text-align: center;
transition: transform 0.3s;
}
.feature-card:hover {
transform: translateY(-5px);
}
.feature-card h4 {
color: #2c3e50;
margin-bottom: 1rem;
}
/* 关于页面样式 */
.about-section {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.about-section h2 {
color: #2c3e50;
margin-bottom: 1rem;
}
.about-section h3 {
color: #2c3e50;
margin: 2rem 0 1rem 0;
}
.about-section ul {
margin-left: 2rem;
}
.about-section ul li {
margin-bottom: 0.5rem;
}
/* 页脚样式 */
footer {
background: #2c3e50;
color: white;
text-align: center;
padding: 2rem 0;
}
/* 响应式设计 */
@media (max-width: 768px) {
.nav-container {
flex-direction: column;
gap: 1rem;
}
.nav-container ul {
gap: 1rem;
}
.nav-container ul li {
margin: 0;
}
.hero-section h2 {
font-size: 2rem;
}
.features-grid {
grid-template-columns: 1fr;
}
}3. 配置静态文件
在 mywebsite/settings.py 中确认静态文件配置:
import os
# 静态文件配置
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# 媒体文件配置(如果需要)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')数据库配置
1. 默认SQLite配置
Django默认使用SQLite数据库,配置在 settings.py 中:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}2. 创建超级用户(可选)
python manage.py createsuperuser3. 数据库迁移
python manage.py makemigrations
python manage.py migrate运行开发服务器
1. 启动服务器
python manage.py runserver2. 访问网站
打开浏览器访问:
3. 停止服务器
按 Ctrl+C 停止开发服务器
部署准备
1. 生产环境设置
创建 requirements.txt 文件:
pip freeze > requirements.txt2. 环境变量配置
创建 .env 文件用于敏感信息:
SECRET_KEY=your-secret-key-here
DEBUG=False
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com3. 更新settings.py以支持环境变量
import os
from decouple import config # pip install python-decouple
# 安全设置
SECRET_KEY = config('SECRET_KEY', default='your-fallback-secret-key')
DEBUG = config('DEBUG', default=True, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='127.0.0.1,localhost').split(',')
# 静态文件收集
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')4. 收集静态文件
python manage.py collectstatic常用Django命令参考
# 项目管理
django-admin startproject projectname
python manage.py startapp appname
# 数据库
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
# 开发服务器
python manage.py runserver
python manage.py runserver 0.0.0.0:8000
# 其他
python manage.py shell
python manage.py collectstatic
python manage.py check下一步学习建议
完成这个基础网站后,您可以继续学习:
- Django模型(Models): 数据库操作和ORM
- Django表单(Forms): 用户输入处理
- 用户认证: 登录、注册功能
- Django REST Framework: API开发
- 缓存系统: 提高网站性能
- 测试: 编写单元测试和集成测试
- 部署: 使用Gunicorn、Nginx等部署到生产环境
总结
通过这个手册,您已经学会了如何:
- 创建Django项目和应用
- 编写视图函数和URL路由
- 使用模板系统创建动态HTML页面
- 处理静态文件(CSS、JavaScript、图片)
- 配置数据库
- 运行开发服务器
这个简单的单主页网站为您提供了Django开发的基础框架,您可以在此基础上添加更多功能和页面。
常见问题
- Q: 一直有自动访问
/c_hello?asker=backuper - A: 端口占用