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.

2
  • 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 Commented Jul 18, 2016 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 Commented Jul 18, 2016 at 22:58

2 Answers 2

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'

Sign up to request clarification or add additional context in comments.

16 Comments

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.
Am I loading this right into my html template? { % load staticfiles %} <script src = "{% static 'admin/js/platformddown_script.js' %}"></script>
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.
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.
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
|
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.

5 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.