0

I am using Django 1.8 and I am having trouble displaying my JavaScript and CSS when I run the development Django server. I think the main problem is not having a good understanding of what to set my static root and static root dir as. I have noticed that my folder/file paths are created differently compared to others when I create a Django project and app. What would I make my STATIC_ROOT and STATICFILES_DIR be assigned to?

Settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(_file_)))
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Myapp'
)

ROOT_URLCONF = 'MyProject.urls'
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates' )],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")

urls.py:

from django.conf.urls import include, url
from django.contrib import admin
from Myapp.views import startpage 
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
# Examples:
# url(r'^$', 'MyProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),

url(r'^admin/', include(admin.site.urls)),
url(r'^$', startpage)
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

views.py:

from django.shortcuts import render, render_to_response

# Create your views here.
def startpage(request):
return render_to_response('htmlpage.html');

Here is my current directories:

C:\Users\Me\DjangoProjects\
                           |-----MyProject\
                                         |------MyApp\
                                                       |----_init_.py
                                                       |----admin.py
                                                       |----models.py
                                                       |----tests.py
                                                       |----views.py
                                                       |----_pycache_\
                                                       |----migrations\
                                         |------MyProject\
                                                       |----_init_.py
                                                       |----settings.py
                                                       |----urls.py
                                                       |----wsgi.py
                                                       |----_pycache_\
                                         |------staticfiles\
                                         |------templates\
                                                       |----htmlpage.html
                                         |------db.sqlite3
                                         |------manage.py

I also don't know where I would put my JSON file, because I am using jquery/javascript to grab data from the JSON file. Also, my javascript code is embedded within my html file, is that okay or do I need to make a separate javascript file?

Any help would be much appreciated. Thank you.

MADE UPDATES.

Carbon
  • 143
  • 5
  • 17
  • As for your static files, you need to add an extra urlpattern (in dev env) : static(settings.STATIC_URL, document_root=settings.STATIC_ROOT), [here in the doc](https://docs.djangoproject.com/en/1.9/howto/static-files/) – Ugo T. Jul 18 '16 at 20:23
  • I added that extra URL pattern. I'm just stuck on figuring out how to display my JSON file data that I am grabbing with embedded JavaScript/JQuery within my HTML file – Carbon Jul 18 '16 at 22:58

2 Answers2

0

Okay, answering your question in the reverse order of your questions.

Firstly, its always a better convention and practice to keep your html, javascript and css in separate files. So all your HTML files goes in the templates directory and the javascript and CSS in js and css directory inside static directory.

Now, I don't think you'll be requiring to access some json file everytime your web-app is loaded. If it is, then again its something wrong as for that purpose, you have your database. So move that data to your DB. Else if it is for one time purpose, say data upload, then you can keep it inside a directory say json inside the static directory.

Now lastly, coming to your main question of STATIC_ROOT vs STATIC_DIRS vs STATIC_URL, then there already is an excellent explanation of the same here-> Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT

plus you need to rename your 'staticfiles' directory to 'static' as in your settings.py you have mentioned the STATIC_URL = '/static/' and not /'staticfiles'/ or else you can change the STATIC_URL = /'staticfiles'/, but the former is a followed convention, so try stick to that.

Community
  • 1
  • 1
Ankush Raghuvanshi
  • 1,392
  • 11
  • 17
  • Okay, I changed the directory from staticfiles to static. I just want to use the JSON file to display data on the page. Its mainly for testing purposes. Where would I put the JSON file inside my Django project? – Carbon Jul 18 '16 at 22:47
  • You can create a folder named json inside the static folder and keep your json file there, but again, my point being that there is no way you can serve/include a json file in your html template the way you can include your js or css file in the head of your html file js and css files have frontend logic written in it, whereas your json file has simply data in it, be it for only testing purpose Hence the data in your json file should actually come from database->models.py->views.py->(js->html) or (html) depending on whether you are rendering data directly to html or returning as HTTPResponse. – Ankush Raghuvanshi Jul 19 '16 at 05:13
  • Well my goal was to be able to bring data from my database into a JSON file, from the JSON file being able to dynamically display the data onto my html page using javascript and GetJSON methods/Jquery. So I can simply just put my JSON data within the JSON folder inside my static directory, but what would I need to change in settings.py in order for this to work? – Carbon Jul 19 '16 at 15:59
  • Why do you need an extra step of writing data into JSON? I mean that's not how it works. You need to write your logic in views.py to read data from your database, and if you want to send it to your javascript or html file in JSON format then obviously you can use serializers. There is no point in first reading from database, then writing to JSON and then reading that JSON from javascript or HTML, when you can directly read the info from DB in views in render that info to javascript or html templates directly. – Ankush Raghuvanshi Jul 19 '16 at 16:21
  • This is just for testing purposes. I want to see if I can pass in my JSON file somehow and utilize my getJSON within my javascript and display the data from JSON to my template. I already have my json directory within my static directory. Is there anyway I can import my Json file? – Carbon Jul 21 '16 at 21:38
0

This is the solution to your problem of reading data from a json file using your javascript in general i.e., it is not dependent on django or php or something like that.

function getAllSupportedItems( ) {
    return $.getJSON("staticfiles/json_folder/name_of_your_json_file.json").then(function (data) {
        return data.items;
    });
}

getAllSupportedItems().done(function (items) {
    // you have your items here
});

See this for a better explanation -> Using Jquery to get JSON objects from local file

One more thing, which you might get stuck if you overcome this problem.

In your settings.py you have mentioned your STATIC_URL = '/static/' whereas you've named that folder as 'staticfiles'. So either you rename your 'staticfiles' to 'static' or vice-versa. Though former is the convention, so rename it to 'static' else your settings.py will look for a folder named 'static' in the BASE Directory, but it will never find one as you have named it 'staticfiles'

Community
  • 1
  • 1
Ankush Raghuvanshi
  • 1,392
  • 11
  • 17
  • Thank you but I have already written a Jquery function using getJSON to populate my jstree and dropdown menus with data from the JSON file. I just don't know how to make it work with Django. I used XAMPP and apache server it came with so I would just put all of my files inside the htdocs and everything would work. I guess I just don't know how to use the appropriate tags for Django etc. – Carbon Jul 22 '16 at 21:19
  • Am I loading this right into my html template? { % load staticfiles %} – Carbon Jul 22 '16 at 21:26
  • Are you getting any specific error or is its just that you are not able to load your static files in your html? Because in my answer I mentioned the same thing that you might get stuck coz of the STATIC_URL thing. – Ankush Raghuvanshi Jul 22 '16 at 21:47
  • I renamed the 'staticfiles' folder to 'static' and my STATIC_URL = '/static/'. I am just not getting data from my JSON to populate my dropdown list like it used to when I wasn't using Django. – Carbon Jul 22 '16 at 21:51
  • When I run server from cmd, I get these errors : "GET /OSTypeddrop_script.js HTTP/1.1" 404 2204 Which is the name of my javascript I am also using to load my JSON data into – Carbon Jul 22 '16 at 21:52
  • This is a 404 error which means it is not able to find your OSTypeddrop_script.js file. – Ankush Raghuvanshi Jul 22 '16 at 21:53
  • Replace your { % load staticfiles %} with this -> {% load static from staticfiles %} and let me know if you are still getting the error. – Ankush Raghuvanshi Jul 22 '16 at 21:54
  • Are your other static files loading.? – Ankush Raghuvanshi Jul 22 '16 at 21:59
  • I am getting the same errors with all other static files. Same 404 error in cmd just different javascript file names – Carbon Jul 22 '16 at 22:01
  • Does your setting.py looks exactly the same as it is in your question? If the answer is yes then you have not mentioned STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] in it. Do that. – Ankush Raghuvanshi Jul 22 '16 at 22:07
  • Also you have two defined two different values of STATIC_ROOT in your settings.py. Moreover if you are running your app on local development server i.e., on Python-Django server and not on any Apache or NGIN-X server, then you don't really need the STATIC_ROOT url. Coz STATIC_ROOT is the folder where every static files will be stored after a you make a python manage.py collectstatic command which is not required in when using Django server. See this for a better understanding -> http://stackoverflow.com/questions/24022558/differences-between-staticfiles-dir-static-root-and-media-root – Ankush Raghuvanshi Jul 22 '16 at 22:13
  • yes it looks like that, now I just added STATIC_DIRS but I still don't get the json data to populate the dropdown menu, this is what I get when I run the server in cmd: django.core.exceptions.ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting [22/Jul/2016 15:13:45]"GET /static/static/admin/js/platformddown_script.js HTTP/1.1" – Carbon Jul 22 '16 at 22:15
  • yes, I'm not using the other static root(I commented it out). I'm using this as static root : STATIC_ROOT = os.path.join(BASE_DIR, "static/") – Carbon Jul 22 '16 at 22:16
  • STATIC_ROOT and STATICFILES_DIRS can't have the same value. Comment out STATIC_ROOT in your settings.py if you are running only the local development server i.e., the Django server. And if you using some other server then you need to create another folder say 'static_root_files ' at the same level as that of 'static' folder and change the STATIC_ROOT to os.path.join(BASE_DIR, 'static_root_files'). So now when you run python manage.py collectstatic, all your static files will get collected in this 'static_root_files' folder. – Ankush Raghuvanshi Jul 22 '16 at 22:26
  • wow. you are awesome. It works!! Thank you so much for all of your time, effort, and patience with me! – Carbon Jul 22 '16 at 22:31
  • There was a day when I was in your shoes. So I understand the importance of a mentor in keeping a student motivated towards learning. Happy to help. :) – Ankush Raghuvanshi Jul 22 '16 at 22:35