简体   繁体   中英

Django, displaying a view in an another view?

I would like to know if I can display a view inside another view with django.

This is what I tried to do:

def displayRow(request, row_id):
    row = Event.objects.get(pk=row_id)
    return render_to_response('row.html', {'row': row})

def listEventsSummary(request):
    listEventsSummary = Event.objects.all().order_by('-id')[:20]
    response = ''
    for event in listEventsSummary:
        response += str(displayRow('',event.id))
    return HttpResponse(response)

The output looks like what I was expecting but I have had to replace the request value with an empty string. Is that fine or is there a better way to do it?

http response contains headers along with html, or anything else, so you can't just add them up like strings.

if you want to modularize your view function, then have sub-procedure calls return strings and then you can do it the way you propose

Probably in your case it would be better to put a loop showing rows into the template, then you won't need the sub-view and the loop in your main view.

def listEventsSummary(request):
    listEventsSummary = Event.objects.all().order_by('-id')[:20]
    return render_to_response('stuff.html',{'events':listEventsSummary})

and in stuff.html

{% for event in events %}
    <p>{{event.date}} and whatever else...</p>
{% endfor %}

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