Using jQuery locally with Bootstrap for Django wont respond - python

I have this in my base.html file included
{% load bootstrap4 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
And I'm using navbar navbar-expand-lg navbar-light from Bootstrap for my navbar.
This is working. When I'm using a small display (like smartphone) it shrinks the menu to dropdown element with a button to expand.
But the {% bootstrap_javascript jquery='full' %} part is taking too long to fully load the jquery source from network:
Around 400ms without cache. I would like to lose this waiting time as much as possible.
So I downloaded latest jquery 3.6.0 from official site, saved it locally in my static files like
static/main_app/scripts/jQuery.js
loaded it locally with
<script type="text/javascript" src="{% static 'main_app/scripts/jQuery.js' %}"></script>
in my base.html. This works and jQuery is working fine. But the Bootstrap's nav-bar buttons are not responding.
There is also not error message in browser's console.
So I though: Maybe the jQuery version is wrong?
So I tried to implement again working version to my site
{% bootstrap_javascript jquery='full' %}
, look for source of the file above in dev-tools of my browser, copy & pasted the source code to my jQuery.js file and loaded the site again. Nothing changed and the navbar still not working.
Is there something I'm missing?
*** UPDATE ***
It works when I set
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
but with
{% load bootstrap4 %}
IT means I'm loading bootstrap two times...

I was able to overwrite BOOTSTRAP4 pip package settings (jquery call) from CDN to local file in settings.py like this
BOOTSTRAP4 = {
"jquery_url": {
"url": f"{STATIC_URL}main_app/scripts/jquery.js",
},
}
Also here are another options to overwrite as well

Related

Django Static Files sometimes load, sometimes not load

I am developing a django app in which i have made a static folder in app folder. I am encountering a problem related to static file. The problem is that while i run the app by runserver command, django does collect static files but when i change something in those static files sometime file gets updated and sometime does not get updated and instead it collects old version of those files even if i save the file and run the app again by runserver command. When I rename the static files (both css and js files) and change the index.html as per new names, the app works totally fine with updated file names for a while and i face this problem again and again. I am tired of renaming the files and not got any proper solution to this problem. I will be thankful for your opinion and help.
The folders of my app look like this:
├───.vscode
├───Project
└───manage.py
└───Project
└───__pycache__/
└───__init__.py
└───asgi.py
└───setting.py
└───urls.py
└───wsgi.py
├───templates
│ └───base.html
└───AppName
└───templates
└───index.html
└───static
└───AppName
└───js
└───indexjs.js //--> This file gets loaded with updated version and sometimes not
└───css
└───style.css //--> This file gets loaded with updated version and sometimes not
└───views.py
└───models.py
└───urls.py
.
.
.
.
static files setting in settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'AppName/static')]
static file settings in my index.html file looks like :
{% extends 'base.html '%}
{% load static %}
{% block content-style-1 %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="{% static 'AppName/js/jquery-3.5.1.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'AppName/css/style.css' %}">
<script src="{% static 'AppName/js/indexjs.js' %}"></script>
{% endblock %}
{% block content-1 %}
<div class="main">
<p>To do App Django-1</p>
</div>
<div class="main-container-1">
<input type="text" id="textbox-1" name="name" width="50px">
<button type="button" id ="btn-2" class="btn btn-primary">Create</button>
</div>
<div class="card mb-1" id="task-card-id">
<div class="card-body"><p>Card Content</p><button type="button" id="btn-3" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
{% endblock %}
Sometimes you have to hard refresh the browser to see the changes, especially if it's Chrome. Try deleting the cookies as well to see if the problem stops. What I do sometimes is open the same page in another browser for direct comparison.
You can hard refresh by holding down ctrl and clicking the reload icon.
Sometimes, the CSS doesn't update because it is saved in the cache. When you edit the CSS, try to clear cache by doing (if you are on google chrome):
At the top right, click More .
Click More tools. Clear browsing data.
Next to "Cookies and other site data" and "Cached images and files," check the boxes.
Click Clear data.
What do you mean by "file gets updated" ? Do you mean you can see the effect of changes in the browser?
If yes, I have the same issue wirh Firefox. It has nothing to do with the development server (runserver) but Firefox does not reload css files in a reliable way. Even when restarting. With other browsers I never had that issue.
You can try to empty cache with addons. I read about forced reload in Firefox with Shift+reload (or Ctrl?), but it did not always work in my case.

JSignature Field Not Appearing in Django

First time posting on the site, apologies before hand as I am a newbie.
Building a Django project in Visual Studio for a class and need a signature form to appear on one of the pages. Currently been following this guide: https://pypi.org/project/django-jsignature/ but have hit a roadblock as all I can get to show on the page is a save button. Below I've listed what I've got.
forms.py
from django import forms
...
from jsignature.forms import JSignatureField
from jsignature.widgets import JSignatureWidget
...
class SignatureForm(forms.Form):
signature = JSignatureField()
template.html
{% extends "app/layout.html" %}
{% block content %}
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
{{form.media }}
<form action="." method="POST">
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
<input type="submit" value="Save"/>
{% csrf_token %}
</form>
</body>
{% endblock %}
views.py
from jsignature.utils import draw_signature
from app.forms import SignatureForm
...
def signature(request):
assert isinstance(request, HttpRequest)
return render(
request,
'app/template.html',
{
'title':'About',
'message':'Your application description page.',
'year':datetime.now().year,
}
)
def my_view(request):
form = SignatureForm(request.POST or None)
if form.is_valid():
signature = form.cleaned_data.get('signature')
if signature:
#as an image
signature_picture = draw_signature(signature)
#or as a file
signature_file_path = draw_signature(signature, as_file=True)
Again, when taken to my template page all that populates is a lone save button. I included this in the body of my layout html page as I had read it could be an issue with running the script on the page but still no luck.
<script src="ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Can anyone point me in the right direction? Hopefully I have provided sufficient info.
I had the same problem. I fixed it by changing where I put {{ form.media }}.
Documentation says to put it above the form, I instead inserted it bellow all my other JS imports.
base.html
.
.
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"</script>
{% block extra_javascript %}{% endblock %}
form-template.html
{% extends "base.html" %}
{% crispy form main_helper%}
{% block extra_javascript %}
{{form.media}}
{% endblock %}
I know this is old, but I just installed django-jsignature and had the same issue. I am new to Django and would like to share the solution to those that are also new to Django and want to use django-jsignature in their project.
There are a few things you have to check.
First, use Chrome, then go to Developer Tools. Check your console and see if you have Javascript errors. If you do, you have to modify 2 files.
The 2 files you have to modify can be found at https://github.com/fle/django-jsignature/pull/11/commits
Reload your template page, and see if you still have javascript errors on your page.
I am using jQuery Core 3.4.1. and this is working great for me with no errors. I have placed the jquery script link on the head section of my html page.
Remove all other javascript dependencies just to make sure they are not conflicting.
Now if you no longer have javascript errors and you still don't have a signature pad, move to step 2.
Load your html template in Chrome and View Page Source. On where you're supposed to have the signature section, you should see a "hidden" div with in the form. That means that the form loaded correctly in html, but your CSS may cause this section not to display correctly.
If that is the case, try creating a new template and just have the jsignature template code in it without any CSS just to test.
If you do not see a "hidden" div on your signature template html when clicking on View Page Source, that means you're page did not render correctly.
a. On your views.py, make sure you add {'form': form } in your context. This instruction was not included in the Readme.
example: return render(request, 'your_signature_template.html', {'form': form }
b. On your signature_template html file, make sure you have {{ form.media }} on top of your form.
Follow exactly what's in the django jsignature tutorial on the pypi site and just make sure you have the latest version of jquery in the head tag of your template. And also dont forget to pass an empty instance of the Signature form to your render method through to your template
I made a demo. Checkout https://djsign.herokuapp.com
And you can find the codes at https://github.com/mnnlthmpsn/djsignature.git
Same Problem, different solution:
I tried to embed the sign-field in a modal, where AGBs should be shown and signed.
Beforehand i made sure that the signaturefield would show up correctly when using nothing but the example-case by fle plus my own base with header and sidebar. There, everything was working allright.
When trying to embed it into another page (with or without being in a modal), the Signaturefield would not show up, but DevTools (Chrome) showed that it loaded correctly.
I saw the size properties of the field being "ratio" for "height" and "width", and fixed "height" to 200px. Then everything worked all right.
forms.py:
from django import forms
from .models import Signature
from jsignature.widgets import JSignatureWidget
from jsignature.forms import JSignatureField
class SignatureForm(forms.ModelForm):
signature = JSignatureField(widget=JSignatureWidget(jsignature_attrs={'color': '#e0b642', 'height': '200px'}))
class Meta:
model = Signature
fields = ['signature']

Django Chartit graph not displaying. Jquery issue?

There are about another 4-5 other posts with the same issue I have but either a.) the solution does not work for me or b.) there are no suggested solutions. I'm hoping someone can help me out with this. Using Chartit and looks like I am passing my object's data properly and I've got my template hitting all the necessary JavaScripts finally and now I am getting this issue from the console:
VM49842 chartloader.js:3 Uncaught ReferenceError: $ is not defined at VM49842 chartloader.js:3
highcharts.js:10 Uncaught Error: Highcharts error #13: www.highcharts.com/errors/13
at Object.a.error (highcharts.js:10)
at a.Chart.getContainer (highcharts.js:250)
at a.Chart.firstRender (highcharts.js:265)
at a.Chart.<anonymous> (highcharts.js:241)
at a.fireEvent (highcharts.js:30)
at a.Chart.init (highcharts.js:240)
at a.Chart.getArgs (highcharts.js:239)
at new a.Chart (highcharts.js:239)
at Object.<anonymous> (VM49842 chartloader.js:5)
at Function.each (jquery.1.7.2.min.js:2)
Here is the line in reference to chartloader.js line 3:
$(document).ready(function()
I've read that it could possibly be interfering with other scripts but I've got no other javascript on my Django project besides what's included in the admin portal.
Settings.py has 'chartit' in installed apps and because I've also heard that scripts could be loading slower than expected from https I've installed them all locally in my static directory and I've run 'python manage.py collectstatic' to install/move them to the proper static directory.
If it's possibly my model's information I can share that if necessary but if I view source it seems to be passing the correct information successfully.
Template - history_graph.html
{% load static %}
{% load chartit %}
{{ graph_display|load_charts:'container' }}
<script type ="text/javascript" src ="/static/js/jquery.1.7.2.min.js"></script>
<script type ="text/javascript" src="/static/js/highcharts.js"></script>
<div class='container'>{{ graph_display|load_charts:'container' }}</div>
The script references needed to be placed in front of the chartit load variable (not the highcharts script reference as previously answered in other questions). Here is the working arrangement:
{% load static %}
<script type ="text/javascript" src ="/static/js/jquery.1.7.2.min.js"> </script>
<script type ="text/javascript" src="/static/js/highcharts.js"></script>
{% load chartit %}
{{ graph_display|load_charts:'container' }}
This cleared the error for chartloader/jquery error where jquery was loading after chartit. IMO this isn't clearly stated and/or stated at all in the documentation. I was still receiving an error for highcharts though until I noticed that:
<div class='container'>
should instead be:
<div id='container'>

How to use autoescape off AND static variables inside django template

I'm using auto generated HTML which has been saved to a file and then read in again to use as part of a page in a django template.
In order to do this I have used:
{% autoescape off %}
{{ my_html }}
{% endautoescape %}
However, in the my_html variable, I have some static content. This comes in the form of something like this:
<img src="{% static "img/tree_report.png" %}" width="12px" height="12px"/>
My issue is that the static content is not displayed. I get:
http://127.0.0.1:8000/%7B%%20static 404 (in the browser error report)
I read something about get_static_prefix in another question but that doesn't solve my problem because I just get this instead:
GET http://127.0.0.1:8000/%7B%%20get_static_prefix%20%%7Dimg/tree_report.png 404 (Not Found)
I also tried endautoscape turning on and off periodically in my_html in the saved HTML variable. That also didn't work.
Should I be autogenerating the development and production static files paths for my_html or is there a more elegant solution to this problem?
Any suggestions are most welcome.
Thanks.

Adding css/js files to the home site in the admin's panel django

I am trying to add a simple script to my admin's panel in django. I am following this example from the doc, which works when I do this:
class ArticleAdmin(admin.ModelAdmin):
class Media:
js = ("my_code.js",)
admin.site.register(Article, ArticleAdmin)
my_code.js (which lives in STATICFILES_DIRS) gets executed when I open the "Article" link in the admin's panel (so this would be the example url: localhost:8000/admin/news/article/)
However, I want it to be executed in the home site, as in right after I login to the admin's panel (this would be the url:localhost:8000/admin/) . Where do I have to insert the class Media then?
Are you trying to make your custom javascript appear on all admin pages? Then the best thing to do is to override the default admin templatte.
Look in your django installation and find django/contrib/admin/templates/admin/base.html make a copy of it in templates/admin in your project folder. Then simply add the following to the html.
<script scr="my_code.js" type="text/javascript"></script>
Then the js will be available on all admin pages.
I found another way which is overriding instead of replacing as explained in here.
If you place the file base.html into templates/admin:
{% extends "admin/base.html" %}
{% load static %}
{% block footer %}
{{ block.super }}
<script type="text/javascript" src="{% static 'my_code.js' %}"></script>
{% endblock %}
This will insert the script after the footer in the at localhost:8000/admin/.
Here I am "overriding" the base.html. But since I am using .super (explained here) it adds the script after the footer tag.

Categories

Resources