Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - placing and accessing a js file in root directory

Tags:

django

I am trying to implement Firebase cloud messaging push notifications in my Django project. Firebase would look for a js file named firebase-messaging-sw.js in a project' root directory (no matter, what sort of project it is).

So, the problem is that I can't figure out what is my project's root directory (sorry, for being stupid), and how to make Firebase see this file. Just as an experiment, I copy-pasted the js file to each and every folder of my project, and still no success (Firebase service can't see the file).

Here's my settings.py file (with relevant content):

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

ROOT_URLCONF = 'android_blend.urls'

WSGI_APPLICATION = 'android_blend.wsgi.application'
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

STATIC_URL = '/static/'

if DEBUG:
    MEDIA_URL = '/media/'
    STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","static-only")
#STATIC_ROOT = [os.path.join(BASE_DIR,"static-only")]
    MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","media")
#MEDIA_ROOT = [os.path.join(BASE_DIR,"media")]
    STATICFILES_DIRS = (
        #os.path.join(os.path.dirname(BASE_DIR),"static","static"),
        os.path.join(BASE_DIR,"static"),
    )

My Django project layout is like this:

android_blend
   android_blend
      settings.py
      url.py
      wsgi.py
   app1
   app2
   ...
   appN
   manage.py

So the question is, what should I do in order for an outside service app (Google Firebase) be able to see the javascript file ?

In my browser, I get the following error:

A bad HTTP response code (404) was received when fetching the script.

like image 320
Edgar Navasardyan Avatar asked Jan 03 '23 19:01

Edgar Navasardyan


1 Answers

I was also facing the same problem.

I tried it in the following way:

Add the following line in urls.py

url(r'^firebase-messaging-sw.js', views.firebase_messaging_sw_js),

Now add the function in view.py file

@csrf_exempt
def firebase_messaging_sw_js(request):
    filename = '/static/firebase-messaging-sw.js'
    jsfile = open(absAppPath + filename, 'rb')
    response = HttpResponse(content=jsfile)
    response['Content-Type'] = 'text/javascript'
    response['Content-Disposition'] = 'attachment; filename="%s"' % (absAppPath + filename)
    return response

So localhost:8000/firebase-messaging-sw.js will work properly...

Hope this will help you...

like image 56
Shreejay Pendse Avatar answered Jan 13 '23 13:01

Shreejay Pendse