How can I add css and jquery file in my django project? - django

I am learning Django for one of my web projects.
Facing difficulties to append css,jquery file in my project.
The template is very simple and need not to use extends.Just one page form.
What I have done to declare my media file that:
In settings.py file:
Added path:
`import os
def path(*x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
`
Then added:
MEDIA_ROOT = path('media') #media is my folder where all the css,js file are
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/media/'
TEMPLATE_DIRS = (
path('templates')
In the urls.py file added:
from django.conf import settings
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root' : settings.MEDIA_ROOT }),
In the template file I have tried with all these types of declaration:
<script type="text/javascript" src="/media/jquery.min.js"></script>
<script type="text/javascript" src="/media/site.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="/media/screen.css" />
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}test.css" />
<link rel="stylesheet" type="text/css" media="screen" href="../media/screen.css" />
But when I loaded the template file as simple html with :
<script type="text/javascript" src="../media/jquery.min.js"></script>
<script type="text/javascript" src="../media/site.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="../media/screen.css" />
That worked.But I need to integrate within my Django project.
Hope will get the navigation and solve it :)
Thanks

The correct syntax is in the list of things you tried unsuccessfully:
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}test.css" />
If you define your MEDIA_URL as "/media/", then that link will work out to be /media/test.css.
Provided that you have the following directory structure:
my_project
|-- settings.py
|-- urls.py
|-- media
|-- test.css
I would double check all your file and directory names, make sure you don't have any errant/extra slashes, etc.
Also, I presume that "test.css" was supposed to be "screen.css" like it was in all your other examples...
But basically, using an absolute url path (starting with the slash to indicate it resolves from the site root) will work just the same as using a relative path (../) as long as you actually have your files in the right place.
Then what you have will work.

My dir structure is as follows:
|-- test_form
|-- /settings.py
|-- /urls.py
|-- /media
| '-- test.css
'-- /templates
'-- ...
And I added the following syntax in my template.html file:
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}test.css" />
I am confused where the problem is.

I think in the urls.py, you might have missed the url in the urlpatterns, i.e.:
urlpatterns = patterns('',url(r'^media/(?P.*)$', 'django.views.static.serve', { 'document_root' : settings.MEDIA_ROOT }),

Related

why are my static files not getting detected in django?

I want to add a static file to my django project app.
My app is named "core"
Hence inside the app where I need the static file (called main.css) , I made a directory named static/core/main.css
So after that my directory looks like this
core
....
-static
|_core
|_main.css
.........
And in the settings.py file , I wrote this
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
And in the html file where I want the static css I wrote this
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %} Welcome | Ecommerce {% endblock %}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.1/css/bulma.min.css">
<link rel="stylesheet" href="{% static 'core/main.css' %}">
This HTML file is located in a global project level template folder where I dump the templates from all the apps in the project .
But my static file is not getting loaded for some reason
May be because you didn't specify the file?
I guess you should change it from
<link rel="stylesheet" href="{% static '' %}">
To
<link rel="stylesheet" href="{% static 'core/main.css' %}">
Try to add
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
into your Django settings
In Your settings.py file add this
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
after that open the terminal in your root directory and run the following command
python manage.py collectstatic
you can also refer to the django documentation where they have explained about staticfiles in django https://docs.djangoproject.com/en/3.2/ref/contrib/staticfiles/

How do i control static directory resources

<script src="./home/static/js/2.d754fc32.chunk.js"></script>
Currently my html file points to this. What static variable django setting.py do I declare to make the HTML point to
<script src="./home/static/static/js/2.d754fc32.chunk.js"></script>
currently in setting.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '../frontend/build')
]
STATIC_ROOT = '/var/www/web/home/static/'
STATIC_URL = 'home/static/'
My build folder contains a static file inside as well.
if STATICFILES_DIR is in the right place:
You just have to {% load 'static' %} on the top of your html (after extend), and to set the css file:
<link rel="stylesheet" type="text/css" href="{% static '/style.css' %}">
if you want a img from there would be:
<img src="{% static '<PathOfImage>/img.png' %}">

Rendering Static file in Wkhtmltopdf in Django

I have followed too many answers to this but I need some more explanation on this topic as I want to know the root cause for it.
I am trying to create pdf using wkhtmltopdf.
This is my setting files look like :
Settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
And the URL to reference static file is :
<link rel="stylesheet" href="{% static '/css/template_pdf.css' %}" type="text/css" />
Or
<link rel="stylesheet" href="/static/css/template_pdf.css" type="text/css" />
or
<link rel="stylesheet" href="file:///static/css/template_pdf.css" type="text/css" />
or
I used this too:
https://gist.github.com/renyi/f02b4322590e9288ac679545df4748d3
and provided url as :
<link rel='stylesheet' type='text/css' href='{{ STATIC_URL }}static/css/template_pdf.css' />
But the issue I understood is, all of the above except last one works perfectly while rendering view :
def view_pdf(request):
"""View function for home page of site."""
context= {'title': 'Hello World!'}
# Render the HTML template index.html with the data in the context variable
return render(request, 'pdf/quotation.html', context=context)
But for creating pdf using wkhtmltopdf it specifically needs the url to be specified like :
<link rel="stylesheet" href="http:localhost:8000/static/css/template_pdf.css" type="text/css" />
I know I am missing something in the static file. But I want to know why it works with rendering template but not with Generating pdf using wkhtmltopdf.
I dont think it is good idea to put directly domain name inside the referencing url.
A detailed solution for this would be helpful as I am very new to django.
I tried follow this answer too but nothing worked : Django wkhtmltopdf don't reading static files
in your settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
WKHTMLTOPDF_CMD = '/usr/local/bin/wkhtmltopdf'
to render static files in your template django provide static tag. You can use this as
<link rel="stylesheet" href="{% static '/css/template_pdf.css' %}" type="text/css" />
Also make sure you have this included in your urls.py
from django.conf import settings
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Don't forget to run collectstatic command in the end
I added http://localhost:8000 explicitly in my template when running in debug mode:
In the template:
<link rel="stylesheet" href="{% if debug %}http://localhost:8000{% endif %}{% static '/css/template_pdf.css' %}" type="text/css" />
And I added the debug to the context:
from django.conf import settings
def view_pdf(request):
"""View function for home page of site."""
context= {
'debug': settings.DEBUG,
'title': 'Hello World!'
}
# Render the HTML template index.html with the data in the context variable
return render(request, 'pdf/quotation.html', context=context)

Django- Staticfiles 404 on runserver

I'm not doing anything fancy. Just trying to get my static files to work using python manage.py runserver with Debug = True
'django.contrib.staticfiles' is installed.
These are my static settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
Here is my template syntax:
{% load staticfiles %}
<title>Dashboard</title>
<!-- Bootstrap Core CSS -->
<link href="{% static "boostrap/bower_components/bootstrap/dist/css/bootstrap.min.css" %}"
rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="{% static "boostrap/bower_components/metisMenu/dist/metisMenu.min.css" %}"
rel="stylesheet">
<!-- Timeline CSS -->
<link href="{% static "boostrap/dist/css/timeline.css" %}" rel="stylesheet">
<!-- Custom CSS -->
<link href="{% static "boostrap/dist/css/sb-admin-2.css" %}" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="{% static "boostrap/bower_components/morrisjs/morris.css" %}" rel="stylesheet">
<!-- Custom Fonts -->
<link href="
{% static "boostrap/bower_components/font-awesome/css/font-awesome.min.css" %}" rel="stylesheet" type="text/css">
findstatic can successfully locate these files when entered exactly as they are in the template:
(AlmondKing) C:\Projects\AlmondKing>python manage.py findstatic bootstrap/bower_components/bootstrap/dist/css/bootstrap.min.css --verbosity 2
Found 'bootstrap/bower_components/bootstrap/dist/css/bootstrap.min.css' here:
C:\Projects\AlmondKing\AlmondKing\static\bootstrap\bower_components\bootstrap\dist\css\bootstrap.min.css
Looking in the following locations:
C:\Projects\AlmondKing\AlmondKing\static
C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\contrib\admin\static
My URLS have no conflict:
ROOT URLS:
urlpatterns = [
url(r'^', include('AlmondKing.AKGenius.urls', namespace="AKGenius")),
url(r'^admin/', include(admin.site.urls)),
url(r'^purchases/', include('AlmondKing.InventoryLogs.urls', namespace="purchases")),
url(r'^company/', include('AlmondKing.FinancialLogs.urls',namespace="company")),
]
AKGenius URLS:
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='home.html'), name="home"),
url(r'^dashboard/$', TemplateView.as_view(template_name='control_panel.html'), name="dashboard"),
url(r'^support/$', 'AlmondKing.AKGenius.views.support'),
]
and the paths seem to be rendering correctly to the browser:
<!-- Bootstrap Core CSS -->
<link href="/static/boostrap/bower_components/bootstrap/dist/css/bootstrap.min.css"
rel="stylesheet">
And yes, I've restarted runserver since my last settings change.
What could be causing these to 404? Would it have something to do with Windows?
And as a proper answer in case anybody else comes across this post at a later date:
Looks like there's a typo in each line, where
{% static "boostrap
should be
{% static "bootstrap

Loading static files in template

I am pretty new to Django and I am trying to put static files in my site but I am unable to do so. I am getting 404 when the browser tries to GET my static files
I'm not sure of the best practices or the correct way for Django to find these static files
Here is a picture of my project structure:
Here is my settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
In my index.html I have a line:
<link href="{{ STATIC_URL }}boothie.css" rel="stylesheet">
<script src="{{ STATIC_URL }}boothie.js"></script>
<script src="{{ STATIC_URL }}jquery.js.1.3.js"></script>
I think this would work:
{% load staticfiles %}
<link href="{% static "css/boothie.css" %}" rel="stylesheet">
<script src="{% static "js/boothie.js" %}"></script>
<script src="{% static "js/jquery.js.1.3.js" %}"></script>
See: Configuring static files
Edit:
You can maintain static files which belong to your home app with the structure like this:
home/
static/
css/
images/
js/
While deploying, you can set STATIC_ROOT to where you want to serve these static files, then run python manage.py collectstatic, django will copy your static files into the STATIC_ROOT directory and you can maintain static files easier (in a single directory) without changing your code.
static_url will give the relative path ....
You may have to include
<link href="{% static "css/boothie.css" %}" rel="stylesheet">