Javascript with Django?

前端 未结 8 1368
日久生厌
日久生厌 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:30

    Actually, you can put your Javascript files (and all your static content) anywhere you want. 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.

    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. Same with 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).

    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).

    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. Just make sure you add that url() to your urlpatterns under a settings.DEBUG is True conditional.

    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.

提交回复
热议问题