DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Mistakes That Django Developers Make and How To Avoid Them
  • Building a Twilio Softphone With JavaScript, HTML, and Flask
  • Checking TLS and SSL Versions of Applications in JavaScript, Python, and Other Programming Languages
  • The Best Programming Languages for Kids

Trending

  • Fraud Detection Using Artificial Intelligence and Machine Learning
  • Testing SingleStore's MCP Server
  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Debugging With Confidence in the Age of Observability-First Systems
  1. DZone
  2. Coding
  3. Languages
  4. How To Use a Python Variable in an External Javascript (Django)

How To Use a Python Variable in an External Javascript (Django)

What if instead of using an HTML template to pass the Django context variable, we inject the variable directly into the external Javascript code.

By 
Fellah A user avatar
Fellah A
·
Apr. 21, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
6.0K Views

Join the DZone community and get the full member experience.

Join For Free

One way to use a Python variable in an external Javascript is to declare the JS variable in the HTML template through the context object, then pass this variable to the external script code :

HTML
 
<script type="text/javascript"> 
  js_var_from_dj = "{{ django_var }}";
</script>
<script src="{% static "js/js_file.js" %}" type="text/javascript"></script>

js_file.js :

JavaScript
 
function functionA(){ 
  //using the variable declared outside this js file
  inner_js_var = js_var_from_dj; 
}

What if instead of using an HTML template to pass the Django context variable, we inject the variable directly into the external Javascript code? 

This is actually possible, the trick here is to wrap the original JS file in a View, and use that view to render the JS file as a Django template.

Our js_file become :

JavaScript
 
function functionA(){
  //using the Django context variable
  inner_js_var = {{django_var}};
}

And the Django views.py :

Python
 
def js_wrapper(request):
    django_var = "a message to js"
    context_for_js = {'django_var ': django_var}
    return render(request, 'path_to_template_folder/js_file.js', context_for_js ,"application/javascript")

We add the view to the URLs list :

Python
 
urlpatterns = [
          path('js_wrapper.js', js_wrapper, name = "js_wrapper.js"), 
         ]

And finally, the external JS file would be declared like this:

HTML
 
<script src="{% static "js_wrapper.js" %}" type="text/javascript"></script>

Exploiting Javascript code as a Django template will potentially elevate client-side code capabilities.

A perfect use case is service worker where you want to set up a set of pages to be pre-cached dynamically, so to avoid hard-coded HTML links to those pages. You can define the list of pages, server-side, and send it to the service worker in a form of a list.

Let's say you want to preload web pages with their specifications for a given user, you can then define the view where you retrieve the product list :

Python
 
def sw_workbox(request):
    product_list = Product.objects.filter(user=request.user)
    context = {'product_list': product_list}
    return render(request, 'sw_workbox.js', context,"application/javascript")

And then pass the pages links to precacheAndRoute()

JavaScript
 
workbox.precaching.precacheAndRoute([
  {% for product in product_list%}    
{url: '{% url 'your_app_name:productModel_change' product.id %}'},
{% endfor %}
});
JavaScript Django (web framework) Python (language)

Published at DZone with permission of Fellah A. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mistakes That Django Developers Make and How To Avoid Them
  • Building a Twilio Softphone With JavaScript, HTML, and Flask
  • Checking TLS and SSL Versions of Applications in JavaScript, Python, and Other Programming Languages
  • The Best Programming Languages for Kids

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!