Template Render is not passing pymongo aggregate v

2019-09-02 08:39发布

问题:

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>