Template Render is not passing pymongo aggregate variable to template

烈酒焚心 提交于 2019-12-11 16:37:44

问题


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 gettheAudit(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'])
            theVs = json.dumps(x['tags']['variables'])
            template = loader.get_template('templates/a.html')
            context = {
                 'theURLs' : theURLs,
                 'theNames' : theNames,
                 'theVs' : theVs,       
            }
       return HttpResponse(template.render(context, request))

My HTML code is pretty simple. I am just trying to print a list of the urls:

   <ul>
      <li><h1>URLSSSS</h1></li>
      {% for theURL in theURLs %}
         <li>{ theURL.theURLs }
      {% endfor %}
   </ul>

My result:

  • URLSSSS
  • {% for theURL in theURLs %} { theURL.theURLs } {% endfor %}

I am new to Django and MongoDb and can't seem to figure out where I went wrong.


回答1:


Trimming this down to just what you're looking for at this point (and correcting some syntax in your template), try a list comprehension:

from django.shortcuts import render

def gettheAudit(request):
    theURLs = [x 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}},])]
    return render(request, 'templates/a.html', {'theURLs': theURLs})

templates/a.html:

   <ul>
      <li><h1>URLSSSS</h1></li>
      {% for theURL in theURLs %}
         <li>{{ theURL }}</li>
      {% endfor %}
   </ul>


来源:https://stackoverflow.com/questions/52397507/template-render-is-not-passing-pymongo-aggregate-variable-to-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!