Django,在另一个视图中显示视图?

时间:2022-02-05 19:41:28

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

我想知道我是否可以使用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?

输出看起来像我期待的但我不得不用空字符串替换请求值。那很好还是有更好的方法呢?

1 个解决方案

#1


4  

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

http响应包含标题以及html或其他任何内容,因此您不能像字符串一样添加它们。

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

并在stuff.html

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

#1


4  

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

http响应包含标题以及html或其他任何内容,因此您不能像字符串一样添加它们。

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

并在stuff.html

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