I have a problem using a js library with django. I am trying to use the particle.js library to generate a particle background for the home page and I have tried following this tutorial.
I have created a particle.json and style.css in my static folder.
UPDATED VERSION (with static files)
home.html
<!-- templates/home.html -->
{% load socialaccount %}
{% load account %}
{% load static %}
<head>
<link rel="stylesheet" href="{% static 'style.css' %}"> </head>
<body>
<div id="particles-js">
{% if user.is_authenticated %}
<p>Welcome {{ user.username }} !!!</p>
<a href="/accounts/logout/" >Logout</a>
{% else %}
Log In with Github
Log In with Twitter
Log In with Facebook
Log In with LinkedIn
{% endif %}
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/particlesjs/2.2.2/particles.min.js"></script>
<script>
particlesJS.load('particles-js', '{% static 'particles.json' %}', function(){
console.log('particles.json loaded...');
});
</script> </body>
defined the static path in settings.py
STATIC_URL = '/static/'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'artemis/static')
]
and im my urls.py file
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('accounts/', include('allauth.urls')),
url('', views.Home.as_view(), name='home'),
] + static(settings.STATIC_URL)
When i start the server, I get the following errors in the console:
GET http://127.0.0.1:8000/static/ net::ERR_ABORTED
Uncaught ReferenceError: particlesJS is not defined
The project structure:
I just started learning django so I know this might sound like a stupid question but any idea what might be going wrong here?
Django can not parse the remainder:
{% static style.css %} this should be {% static 'style.css' %} with quotes
{% static particles.json %} should be {% static 'particles.json' %} with quotes
Related
I know I'm doing something wrong, after consulting the docs and watching 3 YouTube videos that get it spun up in the first 7 min and copying them it still doesn't work
I'm basically trying to get to hello world from clicking a button
The Relevant lines in my HTML
{% extends 'box2.html' %}
{% load static %}
{% block content %}
<button class="btn btn-success mt-3" type="button" onclick="handle_do_thing_click()" type="">Add Planner</button>
{% endblock %}
{% block js_block %}
<script type = "text/javascript/" src="{% static 'js/doThing.js' %}"></script>
{% endblock %}
my settings.py static settings
INSTALLED_APPS = ['django.contrib.staticfiles']
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
my url.py file
from django.urls import path
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [ these work
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
and my js file which exists in app/static/js/doThing.js is hello world
function handle_do_thing_click() {
console.log("hello world");
}
The console error is
Uncaught ReferenceError:
handle_do_thing_click is not defined at HTMLButtonElement.onclick
For me, removing type="text/javascript/" from <script> tag make it work.
In my symfony project my css is well linked, but my javascript is not working and I can't find why. I guess something stupid I missed ...! I tried with the encore webpack at firt since I'm runninh Sass, but I gave up and switched to the classi src=""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{# Run `composer require symfony/webpack-encore-bundle`
and uncomment the following Encore helpers to start using Symfony UX #}
{% block stylesheets %}
{# {{ encore_entry_link_tags('app') }}#}
{# {{ encore_entry_script_tags('app') }}#}
<link rel="stylesheet" href="{{ asset('bundles/mercuryseriesflashy/css/flashy.css') }}">
<link rel="stylesheet" href="{{ asset('./build/app.css') }}">
{% endblock %}
{% block javascripts %}
{# {{ encore_entry_script_tags('app') }}#}
<!-- Flashy depends on jQuery -->
{% endblock %}
</head>
<body>
{% block navbar %} {% include 'inc/navbar.html.twig'%}{% endblock %}
{% block body %}{% endblock %}
{% block footer %}{% endblock %}
<script src="{{ asset('./build/app.js') }}"></script>
<script src="//code.jquery.com/jquery.js"></script>
</body>
</html>
/*
* Welcome to your app's main JavaScript file!
*
* We recommend including the built version of this JavaScript file
* (and its CSS file) in your base layout (base.html.twig).
*/
// any CSS you import will output into a single css file (app.scss in this case)
import './styles/app.scss';
import './bootstrap';
// start the Stimulus application
const logoMenu = document.querySelector('.logoMenuImg');
const contItems = document.querySelector('.contItems');
const arrItems = document.querySelectorAll('.items');
console.log(logoMenu);
console.log(contItems);
console.log(arrItems);
console.log('arrItems');
alert('hello world');
Thank you for your help
p.s: in the inspector it's blank no erros
If you are using encore_entry_script_tags i assume you have add your JS file in your webpack configuration ?
I see you're using assetic, if you are in Symfony 4.4 and more, remove it, it's deprecated. Use Webpack encore.
let Encore = require('#symfony/webpack-encore');
let CopyWebpackPlugin = require('copy-webpack-plugin');
//let TerserPlugin = require('terser-webpack-plugin');
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
.addEntry('app', './assets/js/app.js')
.enableSingleRuntimeChunk()
;
module.exports = Encore.getWebpackConfig();
And run with npm run build or yarn encore <env>
Look at documentation: https://symfony.com/doc/current/frontend.html
I code with django and when I am working with django template, I do the below to avoid repeating code. Let me illustrate it with an example:
Suppose I have two pages in my website:
1) home
2) about
In django I code as below:
I first build a base.html :
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}home{% endblock title %}</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'css/my-base-css.css' %}">
{% block stylesheet %}{% endblock stylesheet %}
</head>
<body>
<h1>this is my site</h1>
{% block body %}{% endblock body %}
</body>
</html>
I then build home.html:
{% extends 'base.html' %}
{% block stylesheet %}<link rel="stylesheet" href="{% static 'css/home-page-css.css' %}">
{% endblock stylesheet %}
{% block body %}
<h2>This is home</h2>
{% endblock body %}
I also build about.html:
{% extends 'base.html' %}
{% block title %}
my-website-about
{% endblock title %}
{% block stylesheet %}<link rel="stylesheet" href="{% static 'css/about-page-css.css' %}">
{% endblock stylesheet %}
{% block body %}
<h2>This is about</h2>
{% endblock body %}
I now want to do the same without having a backend. I have a static website. How can I do the same without having a backend like django or php, etc.?
There is a similar question in here:
Include another HTML file in a HTML file
This can solve my problem. However, it is a little different from what I want. It is loading another html in an html file but I am looking for extending another html; I mean adding to another base.html and having a new html file
It looks like you're using the Django Templating Language which is similar to Jinja (I've only used this one because I've mostly used Flask but the way it works should be similar). Django uses this language in its template engine and the way it works is by basically taking your HTML file, passing it through a backend (Django), and replacing the variables/logic you have there with actual values. In the end, you'll have a fully built HTML file.
The short answer is no.
From my understanding of template engines, you need to have a backend that can actually work out which values (by replacing this syntax { some_variable }) you should put in the final HTML output.
Sorry I couldn't come with a more precise topic title and I must admit I'm still pretty new Django.
I am trying to work with Ajax and templates with splitted views but I can't achieve what I want, one way or another.
My goal is to be able to work with rendered templates and jquery hide/show instructions but I'm failing at some point.
Here is my urls.py:
from django.urls import path
from django.conf.urls import url
from . import views, inventory
urlpatterns = [
path('', views.index, name='index'),
url(r'^inventory', inventory.inventory, name='inventory'),
url(r'^buildInventory', inventory.buildInventory, name='buildInventory'),
]
My views index renders a templated "index.html" (there is a context that I removed for the illustration):
def index(request):
return render(request, 'myapp/index.html', context)
My index.html file :
{% extends "base.html" %}
{% load static %}
{% block delivery_form %}
<div id="mainblock">
....
</div>
{% endblock %}
And my base.html mostly contains my statics & headers:
{% load static %}
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="shortcut icon" type="image/png" href="http://web-iec/favicon.ico"/>
<link rel="stylesheet" type="text/css" href="{% static 'myapp/css/nice.css' %}">
<script type="text/javascript" src="{% static 'myapp/js/jquery.js' %}" ></script>
<script type="text/javascript" src="{% static 'myapp/js/jquery-ui.js' %}" ></script>
<script type="text/javascript" src="{% static 'myapp/js/inventory.js' %}" ></script>
<script type="text/javascript" src="{% static 'myapp/js/homepage.js' %}" ></script>
</head>
<body>
<div class="navBar">
<span class="navBtn" id="listDeplVer" title="Inventory">Inventory</span>
</div>
<div style="min-height: 100%;margin-bottom: -20px;">
{% block delivery_form %}
{% endblock %}
{% block inventory %}
{% endblock %}
</div>
</body>
</html>
Now what I'm trying to achieve, within my inventory.js I've got an onclick event that I'm trying to use to hide the home page content and replace it by the rendered html from my inventory.py view with associated html:
my inventory.py:
def inventory(request):
return render(request, 'myapp/inventory.html')
and my inventory.html:
{% extends "base.html" %}
{% load static %}
{% block inventory %}
<div id="inventoryblock">
// html
</div>
{% endblock %}
Finally my inventory.js is looking like:
$(document).ready(function () {
$( "#listDeplVer" ).click( function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/myapp/inventory',
beforeSend: function(){
$("#mainblock").fadeOut();
},
success : function(output){
$("#inventoryblock").html(output);
},
});
});
So like I said I was expecting that onclick my page's content is replaced by the rendered inventory page, but this is not working.
When using the web developper tools, if I open the XHR request for the inventory in a new tab it work just fine, so I assume I'm doing something the wrong way.
Before merging everything in one single file (js, views, html & so on) I wanted to ask if there is way to have something similar to work ?
Thank you for your help
Your source page doesn't have an "inventoryblock" div. That's only in the page you're loading via Ajax. So when your success function runs, it doesn't know where to put the output.
You need to put an empty div with id "inventoryblock" in your index.html.
Also, your inventory.html probably shouldn't inherit from anything. You don't need the full HTML file with the head block etc, you just want the fragment containing the contents of inventoryblock that you can insert into the requesting page. Remove everything other than the relevant HTML itself.
I want to load a javascript file in the template that extends my base_generic template. I am using generic listView to render the template.
Since I can not use "{% url %}" tamplate tag inside of "{% block %}" tag I hardcoded the link as follows:
<script src="static/js/search.js">
Unfortunately the file does not work and I get a a message that: "SyntaxError: expected expression, got '<' "
I guess it is because my view tries to render the template as html (am I right?) - my assumption is based on this post: SyntaxError: expected expression, got '<'
So my question is: how can I load a static file in the template that extends another template.
EDIT:
Here is my template:
{% extends "base_generic.html" %}
{% block content %}
{% if search_flag %}
SEARCHFLAG ON
{% else %}
<h2 class="myh"> Książki: </h2>
{% if book_list %}
<script>
var lista=[];
{% for book in book_list %}
var title="{{book.title}}";
var authors=[];
{% for author in book.author.all %};
var aut="{{author.last_name}}";
authors.push(aut);
{% endfor %}
var authorsStr=authors.join('; ');
var book=[title, authorsStr]
lista.push(book);
{% endfor %}
console.log("created list of books and authors - name: lista")
</script>
{% else %}
<p>W katalogu nie ma książek</p>
{% endif %}
{% endif %}
<script src="static/js/search.js">
</script>
{% endblock %}
You don't use {% url %} tag to get path to you static file, just write this on the top of your template file:
{% load staticfiles %}
After that, you can get access to your static files by folowing constructions:
<script src="{% static 'js/search.js' %}">
Read more in documentation.
If you want to extend the base template, you have to add block script and extend it to your templates
base.html:
{% block scripts %}
{% endblock %}
index.html:
{% block script %}
<script src="{% static 'js/search.js' %}">
{% endblock %}
Hope this will help.
You can use {% url "" %} in a block. To use static make sure to include {% load static %} directly after the extends template tag when you need it. Then you can:
<script src="{% static 'js/search.js' %}">