0

I built an app using Django 3.2.3., but when I try to settup my javascript code for the HTML, it doesn't work. I have read this post Django Static Files Development and follow the instructions, but it doesn't resolve my issue.

Also I couldn't find TEMPLATE_CONTEXT_PROCESSORS, according to this post no TEMPLATE_CONTEXT_PROCESSORS in django, from 1.7 Django and later, TEMPLATE_CONTEXT_PROCESSORS is the same as TEMPLATE to config django.core.context_processors.static but when I paste that code, turns in error saying django.core.context_processors.static doesn't exist.

I don't have idea why my javascript' script isn't working.

The configurations are the followings

Settings.py

BASE_DIR = Path(__file__).resolve().parent.parent

STATIC_URL = '/static/'  
STATICFILES_DIRS = ( 
      'C:/Users/pansh/Documents/SarahPortfolio/Portfolio/Portfolio/static/',  
      'C:/Users/pansh/Documents/SarahPortfolio/Portfolio/formulario/static/formulario',
)

urls.py

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns  


urlpatterns = [
    path('admin/', admin.site.urls),
    path('formulario/', include("formulario.urls"))
]


from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

Template

{% load static %}

<!DOCTYPE html>
<html lang='es'>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href= "{% static 'formulario/style.css' %}">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  
  <script src="{% static 'formulario/scriptinfra.js' %}" type="text/javascript"></script>    

  <title>Análisis de Infraestructura</title>
</head>

Directory Tree

├───formulario
│   ├───migrations
│   │   └───__pycache__
│   ├───static
│   │   └───formulario
│   ├───templates
│   │   └───formulario
│   └───__pycache__
└───Portfolio
    ├───static
    └───__pycache__

If you could lend me a hand I'll be very thankful.

UPDATE N°1

Once I used python manage.py collectstatic, it says the following error

Type 'yes' to continue, or 'no' to cancel: yes
Traceback (most recent call last):
  File "C:\Users\pansh\Documents\SarahPortfolio\Portfolio\manage.py", line 22, in <module>
    main()
  File "C:\Users\pansh\Documents\SarahPortfolio\Portfolio\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 187, in handle
    collected = self.collect()
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 114, in collect
    handler(path, prefixed_path, storage)
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 338, in copy_file
    if not self.delete_file(path, prefixed_path, source_storage):
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 248, in delete_file
    if self.storage.exists(prefixed_path):
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\files\storage.py", line 318, in exists
    return os.path.exists(self.path(name))
  File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\storage.py", line 38, in path
    raise ImproperlyConfigured("You're using the staticfiles app "
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.

UPDATE N°2

I have replace STATICSFILES_DIRS with the following

STATIC_URL = '/static/' 

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')

Therefore I submited again python manage.py collectstatic, which it gave me this output

You have requested to collect static files at the destination
location as specified in your settings:

    C:\Users\pansh\Documents\SarahPortfolio\Portfolio\Portfolio\static

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes

133 static files copied to 'C:\Users\pansh\Documents\SarahPortfolio\Portfolio\Portfolio\static'.

But I still my javascript scripts are not working

UPDATE 3

I have paste the following into urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('formulario/', include("formulario.urls"))
] +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Javascript'script still not working

UPDATE 4: Final Solution

The solution that I found is the following.

  1. JS was included in the <header>, and in this point the DOM was not loaded yet, so there are two options

    1. Set the <script> tag in the end of the body

    2. Wrap the function with the window.onload handler

In this case I will be using the second option like this:

window.onload = function(){
  const ui = document.forms.infra;
  const io = ui.elements;

  ui.onclick = addRem;

function addRem(event) {
  const clicked = event.target;
  const main = document.querySelector('.container');
  let rows = main.querySelectorAll('.row');
  
  if (clicked.matches('#add')) {
    const row = ` <section class="row"><div class="col-lg-4 mb-2"> <input name='infs' class="form-control" type="text" placeholder="Infraestructura"> </div> <div class="col-lg-4 mb-2"> <input name='time' class="form-control" type="text" placeholder="Tiempo"> </div> <div class="col-lg-4 mb-2"> <input name='cost' class="form-control" type="text" placeholder="Costo Mensual"> </div> </section>`;
    main.insertAdjacentHTML('beforeEnd', row);
  } else if (clicked.matches('#rem') && rows.length > 1) {
    rows[rows.length-1].remove();
  } else {
    return false;
  }
};

Once doing that, I'm able to run the app with JS file working !

I want to thank to Katya and Maik, for being so pacient with me (you guys are awsome !) and thanks @Mohamed ElKalioby for helping me to set the Django settup, I thanks all of you from the botton of my heart.

Thrillidas
  • 79
  • 7

1 Answers1

1

Run ‘python manage.py collectstatic’ and try again.

The way you handle static wrong, remove the static dirs in your INSTALLED_APPS out of STATIC_DIRS and set a STATIC_ROOT then collectstatic again.

Add the following as django documentation to your urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Mohamed ElKalioby
  • 1,908
  • 1
  • 12
  • 13