跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Django代码风格
”︁(章节)
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= Django代码风格 = '''Django代码风格'''是指在使用Django框架开发Web应用时,遵循的一系列编码规范和最佳实践。良好的代码风格不仅能提高代码可读性,还能促进团队协作,减少维护成本。本指南将详细介绍Django官方推荐和社区广泛接受的代码风格规范。 == 介绍 == Django作为一个成熟的Python Web框架,其代码风格主要基于[[PEP 8]](Python的官方风格指南),同时结合框架自身特点形成了一些特定约定。这些规范涉及: * 项目结构组织 * 命名约定 * 代码布局 * 模型设计 * 视图编写 * 模板处理 * 测试规范 == 项目结构 == 标准的Django项目应遵循以下目录结构: <pre> myproject/ ├── manage.py ├── myproject/ │ ├── __init__.py │ ├── settings/ │ │ ├── __init__.py │ │ ├── base.py │ │ ├── development.py │ │ └── production.py │ ├── urls.py │ └── wsgi.py ├── apps/ │ └── myapp/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations/ │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py └── requirements/ ├── base.txt ├── development.txt └── production.txt </pre> 关键特点: * 使用Python包组织项目(包含<code>__init__.py</code>) * 将settings拆分为多个环境专用文件 * 应用存放在专门的<code>apps/</code>目录 * 依赖管理分环境存储 == 命名约定 == === 文件和目录 === * 使用小写字母和下划线(snake_case) * 模板目录:<code>templates/app_name/</code> * 静态文件目录:<code>static/app_name/</code> === Python标识符 === {| class="wikitable" |+ Django命名规范对照表 ! 类型 !! 规范 !! 示例 |- | 模块 | 小写+下划线 | <code>views.py</code> |- | 类 | 大驼峰 | <code>class BlogPost</code> |- | 函数/方法 | 小写+下划线 | <code>get_absolute_url()</code> |- | 常量 | 大写+下划线 | <code>MAX_POSTS = 100</code> |} == 代码组织 == === 模型设计 === <source lang="python"> from django.db import models from django.urls import reverse class Article(models.Model): """博客文章模型""" title = models.CharField( max_length=200, verbose_name="标题", help_text="请输入文章标题" ) content = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, related_name='articles' ) class Meta: ordering = ['-pub_date'] verbose_name_plural = "文章" def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) </source> 最佳实践: * 每个字段单独一行 * 添加<code>verbose_name</code>和<code>help_text</code> * 定义<code>__str__</code>方法 * 使用<code>related_name</code>明确反向关系 * 添加<code>get_absolute_url</code>方法 === 视图编写 === <source lang="python"> from django.views.generic import ListView, DetailView from .models import Article class ArticleListView(ListView): """文章列表视图""" model = Article template_name = 'blog/article_list.html' context_object_name = 'articles' paginate_by = 10 def get_queryset(self): """重写查询集添加过滤条件""" return super().get_queryset().filter( is_published=True ).select_related('author') </source> === 模板处理 === <source lang="django"> {# blog/article_detail.html #} {% extends "base.html" %} {% block title %}{{ article.title }}{% endblock %} {% block content %} <article> <h1>{{ article.title }}</h1> <p class="meta"> 作者: {{ article.author.username }} | 发布于 {{ article.pub_date|date:"Y-m-d" }} </p> <div class="content"> {{ article.content|linebreaks }} </div> </article> {% endblock %} </source> == 测试规范 == <source lang="python"> from django.test import TestCase from django.urls import reverse from .models import Article class ArticleModelTest(TestCase): @classmethod def setUpTestData(cls): """创建测试数据""" cls.article = Article.objects.create( title="测试标题", content="测试内容" ) def test_title_max_length(self): """测试标题最大长度""" max_length = self.article._meta.get_field('title').max_length self.assertEqual(max_length, 200) def test_article_str(self): """测试__str__方法""" self.assertEqual(str(self.article), "测试标题") class ArticleViewTest(TestCase): def test_view_url_exists(self): """测试视图URL可访问""" response = self.client.get('/articles/') self.assertEqual(response.status_code, 200) </source> == 安全实践 == === 查询安全 === <source lang="python"> # 不安全 Article.objects.raw("SELECT * FROM blog_article WHERE title = '%s'" % user_input) # 安全 Article.objects.filter(title=user_input) </source> === 表单处理 === <source lang="python"> from django import forms from django.core.exceptions import ValidationError class CommentForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() content = forms.CharField(widget=forms.Textarea) def clean_content(self): content = self.cleaned_data['content'] if len(content) < 10: raise ValidationError("评论太短") return content </source> == 性能优化 == <mermaid> graph TD A[请求到达] --> B[缓存检查] B -->|命中| C[返回缓存] B -->|未命中| D[数据库查询] D --> E[模板渲染] E --> F[缓存结果] F --> G[返回响应] </mermaid> 关键优化点: * 使用<code>select_related</code>和<code>prefetch_related</code> * 合理使用缓存 * 延迟加载不必要的数据 * 批量操作代替循环 == 代码格式化工具 == 推荐工具组合: * <code>black</code> - 自动格式化代码 * <code>flake8</code> - 检查PEP 8合规性 * <code>isort</code> - 自动排序import语句 配置示例(<code>pyproject.toml</code>): <source lang="toml"> [tool.black] line-length = 88 target-version = ['py38'] include = '\.pyi?$' exclude = ''' /( \.git | \.hg | \.mypy_cache | \.tox | \.venv | _build | buck-out | build | dist )/ ''' [tool.isort] profile = "black" multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 use_parentheses = true ensure_newline_before_comments = true line_length = 88 </source> == 实际案例 == '''电商平台商品模块'''代码风格示例: <source lang="python"> from django.db import models from django.utils.translation import gettext_lazy as _ class Product(models.Model): """商品核心模型""" name = models.CharField( max_length=255, verbose_name=_("商品名称") ) sku = models.CharField( max_length=50, unique=True, verbose_name=_("库存单位") ) price = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_("价格") ) description = models.TextField( blank=True, verbose_name=_("商品描述") ) category = models.ForeignKey( 'Category', on_delete=models.PROTECT, related_name='products', verbose_name=_("商品分类") ) is_active = models.BooleanField( default=True, verbose_name=_("是否上架") ) class Meta: verbose_name = _("商品") verbose_name_plural = _("商品") ordering = ['name'] def __str__(self): return f"{self.name} ({self.sku})" def get_absolute_url(self): return reverse('product_detail', kwargs={'pk': self.pk}) </source> == 总结 == 遵循Django代码风格的主要优势: * 提高代码可读性和一致性 * 减少团队协作中的摩擦 * 便于维护和扩展 * 降低引入安全漏洞的风险 * 优化应用性能 建议开发者: 1. 始终遵循PEP 8基础规范 2. 使用Django内置工具和约定 3. 保持代码风格一致性 4. 定期使用代码检查工具 5. 编写清晰的文档字符串 通过遵循这些最佳实践,您可以构建出更健壮、更易维护的Django应用程序。 [[Category:后端框架]] [[Category:Django]] [[Category:Django最佳实践]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)