简体   繁体   English

Django的Java语言?

[英]Javascript with Django?

I know this has been asked before, but I'm having a hard time setting up JS on my Django web app, even though I'm reading the documentation. 我知道以前已经有人问过这个问题,但是即使我在阅读文档,也很难在Django Web应用程序上设置JS。

I'm running the Django dev server. 我正在运行Django开发服务器。 My file structure looks like this: 我的文件结构如下所示:

mysite/
      __init__.py
      MySiteDB
      manage.py
      settings.py
      urls.py
      myapp/
           __init__.py
           admin.py
           models.py
           test.py
           views.py
           templates/
                index.html

Where do I want to put the Javascript and CSS? 我要将Javascript和CSS放在哪里? I've tried it in a bunch of places, including myapp/ , templates/ and mysite/ , but none seem to work. 我已经在很多地方尝试过了,包括myapp/templates/mysite/ ,但似乎都没有用。

From index.html : index.html

<head>
    <title>Degree Planner</title>
    <script type="text/javascript" src="/scripts/JQuery.js"></script>
    <script type="text/javascript" src="/media/scripts/sprintf.js"></script>
    <script type="text/javascript" src="/media/scripts/clientside.js"></script>
</head>

From urls.py : urls.py

(r'^admin/', include(admin.site.urls)),
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'media'})
(r'^.*', 'mysite.myapp.views.index'),

I suspect that the serve() line is the cause of errors like: 我怀疑serve()行是导致错误的原因,例如:

TypeError at /admin/auth/
'tuple' object is not callable

Just to round off the rampant flailing, I changed these settings in settings.py : 为了消除泛滥,我在settings.py中更改了这些设置

MEDIA_ROOT = '/media/'
MEDIA_URL = 'http://127.0.0.1:8000/media'

UPDATE : I made some changes, but it's still not working: 更新 :我进行了一些更改,但仍然无法正常工作:

settings.py : settings.py

ROOT_PATH = os.path.normpath(os.path.dirname(__file__))

urls.py : urls.py

(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(settings.ROOT_PATH, 'site_media')}),

index.html : index.html

<script type="text/javascript" src="/media/JQuery.js"></script>
<script type="text/javascript" src="/media/sprintf.js"></script>
<script type="text/javascript" src="/media/clientside.js"></script>

Filesystem : 文件系统

mysite/
      site_media/
                JQuery.js
                sprintf.js
                clientside.js
      __init__.py
      settings.py
      manage.py
      -- etc
      myapp/
           -- app files, etc

When I go to a url like http://127.0.0.1:8000/media/sprintf.js , I get: 当我转到http://127.0.0.1:8000/media/sprintf.js类的网址时,我得到:

Page not found: /media/sprintf.js

But does that /media/ global directory exist? 但是该/media/全局目录是否存在? And have you placed in there a scripts subdirectories with the scripts you want to serve from there? 并且您是否在其中放置了scripts子目录以及要从那里提供服务的脚本? What about the /scripts/... url from which you want to serve JQuery.js -- that doesn't seem to be served anywhere from your urls.py . 您想JQuery.js提供JQuery.js/scripts/... url怎么JQuery.js -似乎从urls.py任何地方都无法提供。 If you (for whatever reason) want to serve scripts (or any other statically served file) from several different URL paths, all of those URL paths need to be matched in urls.py with the static-serving -- or else, do the normal things and serve them all from the /media/... root URL, and map that media root to the dir where you actually keep these files (in their respective subdirs, typically). 如果您(无论出于何种原因)想要从几个不同的URL路径提供脚本(或任何其他静态提供的文件),则需要在urls.py中将所有这些URL路径与静态服务进行匹配-否则,请执行正常情况,然后从/media/...根URL将它们全部提供,然后将该媒体根映射到您实际保留这些文件的目录(通常在其各自的子目录中)。

Django's docs about static serving (for development only , since it's documented as Django有关静态服务的文档用于开发,因为其文档记录为

Using this method is inefficient and insecure . 使用此方法效率低下 且不安全 Do not use this in a production setting. 请勿在生产环境中使用此功能。 Use this only for development. 仅将此用于开发。

so beware!-) seems pretty clear to me. 所以要当心!-)对我来说似乎很清楚。

You may want to use absolute path for 'document_root' in urls.py if you want to use the development server to serve static files. 如果要使用开发服务器提供静态文件,则可能要在urls.py中使用'document_root'的绝对路径。 MEDIA_ROOT and MEDIA_URL don't play any role here. MEDIA_ROOT和MEDIA_URL在这里没有任何作用。

Here are my settings for your reference. 这是我的设置供您参考。 I put all static media files under site_media/ 我将所有静态媒体文件放在site_media /下

mysite/
    site_media/
        css/
        js/
        images/
    ...

in settings.py: 在settings.py中:

ROOT_PATH = os.path.normpath(os.path.dirname(__file__))

in urls.py: 在urls.py中:

url(r'^media/(?P<path>.*)$', "django.views.static.serve", {'document_root':
                                      os.path.join(settings.ROOT_PATH, 'site_media')})

You can move static files else where, just need to point 'document_root' to the correct path. 您可以将静态文件移动到其他地方,只需将“ document_root”指向正确的路径即可。 Make sure comment out this url line for production deployment. 确保注释掉该URL行以进行生产部署。

Actually, you can put your Javascript files (and all your static content) anywhere you want. 实际上,您可以将Javascript文件(以及所有静态内容)放置在所需的任何位置。 I mean, Django does not impose a standard on where to place them, after all they won't be handled by Django, they'll be served by the webserver. 我的意思是,Django并未对放置它们的位置施加任何标准,毕竟Django将不会处理它们,而Web服务器将为它们提供服务。

Said that, It's a good idea to keep them somewhere close to the project's files. 话虽如此,将它们保持在靠近项目文件的位置是个好主意。 I'd recommend to keep them in a sibling folder to your Django code. 我建议将它们保存在Django代码的同级文件夹中。 Same with MEDIA_ROOT. 与MEDIA_ROOT相同。

It is a good idea to decouple your static files from python files because now you can put them in totally separate folders in a production environment and easily give different access to static files and python code (say FTP access, or permissions). 将静态文件与python文件解耦是一个好主意,因为现在您可以将它们放在生产环境中完全独立的文件夹中,并轻松地为静态文件和python代码提供不同的访问权限(例如,FTP访问或权限)。

Something to keep in mind is that the settings' MEDIA_ROOT is the place where user's media files (that is uploaded content) will be placed, these are not your static project files, these are whatever files your Django app uploads (avatars, attachments, etc). 需要记住的是,设置的MEDIA_ROOT是放置用户媒体文件(即上内容)的位置,这些不是您的静态项目文件,是Django应用程序上载的任何文件(头像,附件等) )。

Proposed folder structure: 建议的文件夹结构:

mysite.com/
  media/       - User media, this goes in settings.MEDIA_ROOT
  static/      - This is your static content folder
    css/
    js/
    images/
  templates/
  project/     - This is your Django project folder
    __init__.py
    manage.py
    settings.py
    myapp/
      __init__.py
      ...files..py

See the other responses recommendation on using Django's serve() function for development enviroment. 有关使用Django的serve()函数开发环境的其他建议,请参见。 Just make sure you add that url() to your urlpatterns under a settings.DEBUG is True conditional. 只要确保在settings.DEBUG is True下将url()添加到urlpatterns settings.DEBUG is True条件。

As for your templates, it's a good idea to use a context processor to send your static file's path to all your templates. 对于模板,最好使用上下文处理器将静态文件的路径发送到所有模板。

I just remove the '^', "r'static/" instead of "r'^static/". 我只是删除了“ ^”,“ r'static /”而不是“ r'^ static /”。 It's works for me ,good luck. 这对我有用,祝你好运。

url(r'static/(?P<path>.*)$', 'django.views.static.serve',
     { 'document_root': the_path }),

I serve javascript via static. 我通过静态服务JavaScript。 So I have something in my urls.py like 所以我的urls.py中有一些东西

(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.getenv('STATIC_DIR')})

So JS urls look like /static/js/blah.js , CSS urls look like /static/css/blah.css , etc. I have Apache handle the static directory when running in production to avoid any issues with Django's static serving mechanism. 所以JS网址看起来像/static/js/blah.js网址看起来像/static/css/blah.css ,等等。在生产环境中运行时,我让Apache处理静态目录,以避免Django的静态服务机制出现任何问题。

For my development work, I use Django's built-in server, but I read the media files from the same directory as they would be in production (/srv/nginx/sitename/media/). 对于我的开发工作,我使用Django的内置服务器,但是我从与生产环境相同的目录中读取媒体文件(/ srv / nginx / sitename / media /)。 So I clone the exact directory structure of my production server on my computer at home, letting me seamlessly push changes to production without having to change anything. 因此,我可以在家中的计算机上克隆生产服务器的确切目录结构,从而无需更改就可以无缝地将更改推送到生产中。

I keep two different settings.py files, though. 不过,我保留了两个不同的settings.py文件。 My home settings.py file has my local database settings, a different MEDIA_URL setting, and DEBUG set to True. 我的home settings.py文件具有我的本地数据库设置,其他MEDIA_URL设置以及DEBUG设置为True。 I use this in my URLs file to enable the server view for local media (since I don't run nginx on my home computer). 我在URL文件中使用它来启用本地媒体的服务器视图(因为我不在家用计算机上运行nginx)。

In urls.py: 在urls.py中:

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^media/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT}),
    )

From settings.py (note, MEDIA_ROOT must be an absolute path): 从settings.py(注意,MEDIA_ROOT 必须是绝对路径):

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/srv/nginx/<sitename>/media/'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://127.0.0.1:8000/media/'

TEMPLATE_CONTEXT_PROCESSORS = (
    # I've taken out my other processors for this example
    "django.core.context_processors.media",
)

In a template: 在模板中:

<link rel="stylesheet" href="{{ MEDIA_URL }}css/form.css" />{% endblock %}

Filesystems: 文件系统:

/srv/nginx/<sitename>
    /media  <-- MEDIA_ROOT/MEDIA_URL points to here
        /css
            base.css
            form.css
        /img
        /js

Oh, also: if that's a direct copy from your urls.py file, you forgot a comma after your serve view, that's causing your TypeError ;) 哦,也:如果是urls.py文件的直接副本,则您在服务视图后忘记了逗号,这会导致TypeError;)

This is a structure I use in a project separated into multiple apps. 这是我在一个项目中使用的结构,该项目分为多个应用程序。 It's a good practice to adapt this structure right at the start -- you don't want global rearrangement when you need to add another app to your project. 良好的做法是从一开始就调整此结构-当您需要向项目中添加另一个应用程序时,您不希望进行全局重排。

/media
  favicon.ico
  robots.txt
  /upload # user uploaded files
  /js  # global js files like jQuery
  /main_app
    /js
    /css
    /img
  /other_app
    /js
    /css
    /img

Then I use excellent StaticMiddleware from django-annoying to serve files. 然后,我使用django-annoying提供的出色的StaticMiddleware提供文件。 settings.py : settings.py

import os
import annoying

MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "media")
MIDDLEWARE_CLASSES = (
    'annoying.middlewares.StaticServe',
    #...
)

The error 404 occurs because MEDIA_ROOT requires absolute path, not relative. 发生错误404是因为MEDIA_ROOT需要绝对路径,而不是相对路径。 The server is trying to access /media in your filesystem, which is obviously not what you want. 服务器正在尝试访问文件系统中的/media ,这显然不是您想要的。

Try this instead: 试试这个:

import os
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'site_media')
MEDIA_URL = '/media/'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM