简体   繁体   中英

Django not rendering python variable in template

I have a string variable in a Python file that I am trying to render in my HTML template. The variable is called contacts, and in my template, I have {{contacts|default:"null"}}. From the documentation, it seems like that should work, but the template keeps coming up with the null keyword. I've scoured the documentation and found nothing. Probably a super simple thing I'm overlooking that has frustrated me to no end.

In the python file, I'm using an API to get a JSON and unloading it into a dictionary (don't know all the specific terms), where I then extract the value I need into a string:

...
dict_data = dict(json.loads(data))
contacts = str(dict_data["contact_count"])

Then in my HTML file:

<p class="spotbanner">
{{contacts|default:"null"}} spots left!
</p>

Is there something else I'm missing? Something super simple that I just don't understand about Django despite having used this method before? Happy to provide more information.

Poked around a teensy bit more and found an answer. For those like me:

It's not as simple as just rendering the variable. Django doesn't see it until you import the .py file into your views.py. Once you've done that, you'll need to create a context in the method that renders the page. For me, it finally worked once I added:

context = context = {"contacts":contacts}

Maybe a simple example might help you. Calling render_to_string to load a template HTML in Django.

  • Be aware the key name will map to the variable name in the HTML
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})
# {{foo}} will show string 'bar' in HTML 

Referral: https://docs.djangoproject.com/en/3.1/topics/templates/

Accordingly, by your cases, suppose we'll see something like

contacts = str(dict_data["contact_count"])
# if you want to show contact_count --> use {{contact_count}} in HTML
rendered = render_to_string('my_template.html', contacts)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM