【问题标题】:Django folder structureDjango 文件夹结构
【发布时间】:2015-01-25 18:46:25
【问题描述】:

对于 Django 应用程序 (1.7) 中的文件夹,什么是好的结构(最佳实践)? 我不确定将静态数据和文件上传放在哪里。

在我所有的项目中结果都不同,但目前我有这样的东西(我遗漏了一些明显的文件夹/文件):

project/
   bin/
   include/
    ...   
   src/
     manage.py
     main/
      - settings.py
      - urls.py
     signup/

   static/
      static_/
        + css
        + img
        + js
      static/
      templates/
       - index.html
       - base.html 
       - ...
      uploads/

而且,我更喜欢看到像 site.com/css/file.css 这样的 url 而不是 site.com/static/css/file.css ,但不知何故,这似乎比它看起来更复杂。那怎么能做到呢?

【问题讨论】:

    标签: django django-staticfiles django-1.7


    【解决方案1】:

    我在setting.py 中使用以下内容(目前使用 Django v1.6.8)

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    import os
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    #TEMPLATE_DIRS = (os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "static", "templates"),)
    TEMPLATE_DIRS = (
    os.path.join(BASE_DIR,  'templates'),)
    

    这给了我一个文件夹布局

    project/
        manage.py
        project_app/
            - settings.py
            - urls.py        
        someother_app/
            - admin.py
            - models.py
            - views.py
            static/
                css/
                javascript/
         templates
             admin/
             someother_app/
                 - base.html
                 - index.html
        media/
    

    我不确定你说site.com/css/file.css 是什么意思。 <head>base.html 中的 <link rel="stylesheet" href="{{ STATIC_URL }}css/jquery.asmselect.css"> 之类的东西使用 Django 框架来呈现您的 .css 文件。为什么不使用那里的东西?节省时间和精力。

    汤米。

    【讨论】:

      【解决方案2】:

      这里是Two Scoops of Django一书中对Django项目布局的推荐:

      repo_root/
          .gitignore
          Makefile
          docs/
          README.rst
          requirements.txt
          django_project_root/
              manage.py
              media/
              django_app_root/
              static/
              templates/
              config/
                  __init__.py
                  settings/
                  urls.py
                  wsgi.py
      

      并被视为三级项目布局,其中:

      • 顶级 (repo_root):部署所需的高级文件
      • 二级(django_project_root):实际的django项目
      • 第三级(配置):django 项目配置文件。

      关于文件上传,我会将它们从浏览器直接上传到 Amazon S3 文件存储(或类似服务)。否则你会占用带宽和 CPU 时间。或者,如果您必须在媒体文件夹中 ^ 并且出于安全原因,请验证上传的文件类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 2011-01-17
        • 2020-10-08
        • 2021-11-18
        • 2021-04-11
        • 2015-04-06
        • 2014-02-18
        相关资源
        最近更新 更多