Javascript with Django?

前端 未结 8 1266
日久生厌
日久生厌 2021-02-06 19:20

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.

I\'m running the Django de

8条回答
  •  感情败类
    2021-02-06 19:44

    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/). 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. My home settings.py file has my local database settings, a different MEDIA_URL setting, and DEBUG set to 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).

    In urls.py:

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

    From settings.py (note, MEDIA_ROOT must be an absolute path):

    # Absolute path to the directory that holds media.
    # Example: "/home/media/media.lawrence.com/"
    MEDIA_ROOT = '/srv/nginx//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:

    {% endblock %}
    

    Filesystems:

    /srv/nginx/
        /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 ;)

提交回复
热议问题