I have a python script written up that returns a list of values from a database. I want to incorporate that script into my django website that I have created. I have an html file right now in my templates folder that has dictionary values hardcoded but how do I replace the dictionary hardcoded material with the script, lets call it values.py
<script type="text/javascript">
$(document).ready(function() {
var dropDown = [" ", "Run1", "Run2", "Trail1", "Trail2"];
var dropDownID = [" ", "111111", "222222", "333333", "444444", "555555"];
$("#dropDown").select2({
data: dropDown
});
$("#dropDown").change(function() {
$("#dropdownID").val(dropDownID[$("#dropDown option:selected").index()]);
});
});
-
Where's your python script or values.py code ?, please post more info so we can helpjsanchezs– jsanchezs2017年02月01日 22:19:16 +00:00Commented Feb 1, 2017 at 22:19
-
@jsanchezs the python code I put into my project directory and then in a folder called "templatetags" inside is values.py and init.pyVisualExstasy– VisualExstasy2017年02月01日 22:23:17 +00:00Commented Feb 1, 2017 at 22:23
-
Yeah, tags are indeed the way to achieve that but post your python code in the question so we can figure out how it works and understand exactly what you need to guide you throughjsanchezs– jsanchezs2017年02月01日 22:24:58 +00:00Commented Feb 1, 2017 at 22:24
-
@jsanchezs its a rather long script and is connected to other features within the database, if you can just guide me to how to even submit a python script into django that would be appreciated. Lets just use a simple dictionary one like the hardcoded above or we can forget about dictionary and just do a simple hello world scriptVisualExstasy– VisualExstasy2017年02月01日 22:30:22 +00:00Commented Feb 1, 2017 at 22:30
-
@VisualExtasy I think question it's quite different from the code you posted, anyhow i posted you a basic example of how tags work. remember to mark as correct the answer if it helped.jsanchezs– jsanchezs2017年02月01日 22:44:15 +00:00Commented Feb 1, 2017 at 22:44
1 Answer 1
As we talked, tags are the way to achieve that....Let's say you want to do a simple "Hello world" tag, this would be your tag.py code :
tag.py
from django import template
register = template.Library()
@register.assignment_tag
def hello_world(name):
salute = 'Hello' + name
return salute
As you see, you got all the python code there, depending on what you need you may need to import models or anything else from database...assuming you got all that in order as you say, you just create the function, process all code you need and return something (dictionary of data in your case to iterate in template), but for this simple example just a string with the name.
Then, inside your template you load your tag file, and call the function sending the specific parameter to use it later as i show you here :
Template.html
{% load tag %}
<div id="id_div">
{% hello_world 'Foo' as salute_text %}
<strong> {{ salute_text }} </strong>
</div>
Hope it helps to clarify!!