I am trying to pass a variable from pymongo on my views.py to a template. I am not getting any errors but neither is my code being rendered to my template.
views.py:
def getTheA(request):
for x in mycol.aggregate([{"$unwind":"$tags"},{'$match': {'tags.tag.name':'A A',}},{'$project': {'url': 1, 'AR': 1, 'tags.tag.name': 1, 'tags.variables': 1, '_id': 0}},]):
theURLs = x['url']
theNames = json.dumps(x['tags']['tag']['name'])
theVars = json.dumps(x['tags']['variables'])
context = {'theURLs' : theURLs}
return render(request, 'templates/a.html', context)
My HTML code is pretty simple. I am just trying to print a list of the urls:
<ul>
<li><b>URLSSSS</h1></b>
{% for theURL in theURLs %}
<li>{{ theURL.theURLs }} </li>
{% endfor %}
</ul>
My result:
I am new to Django and MongoDb and can't seem to figure out where I went wrong.
When you have {{ xy }}
in a template, that means "attribute or dictionary key y
of object x
".
So, in your template, when you have {{ theURL.theURLs }}
, that means "attribute or dictionary key theURLs
of object theURL
.
theURL
is already looping over each object in theURLs
. Do those objects really have attributes also named theURLs
? Nothing in your code suggests this is the case.
Okay after looking at your code for a long time, there are two main problems.
<li>{{ theURL.theURLs }}</li>
should just be <li>{{ theURL }}</li>
Your for loop is seriously messed up. In its current form, you only take the last URL that you iterate over. Fix it in this way:
def getTheA(request): theURLs = [] for yadayadayada: theURLs.append(x['url']) theNames = json.dumps(x['tags']['tag']['name']) theVars = json.dumps(x['tags']['variables']) context = { 'theURLs' : theURLs } return render(request, 'templates/a.html', context=context)
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.