猿问

Django 后端循环到前端列表

很抱歉这个问题,但我是 Django 的初学者,我找不到任何像这种情况这样的话题。


这是代码:


views.py


def select_collections(request):

    listacolecao = Collection.objects.order_by('upload_date')

        

    listasubscription = Subscription.objects.filter(user=request.user)


    for obj in listacolecao:

                try:

                    Subscription.objects.filter(user=request.user, collection=obj)

                except Subscription.DoesNotExist:

                    print('not exist')

                else:

                    print('Ok')

它在终端打印这个结果:


not exist

not exist

Ok

not exist

Ok

Ok

Ok

Ok

我知道那不是列表,但我需要将其结果放入模板中。我怎样才能做到这一点?


狐的传说
浏览 141回答 1
1回答

三国纷争

如果你只是想要你在那里拥有的相同但打印在你拥有的模板中,(以我的谦虚和初学者的观点)你需要稍微修改你的视图,创建一个你想要显示它的模板并将 url 修改为在该模板中加载视图,例如:查看.py 变化:def select_collections(request):&nbsp; &nbsp; listacolecao = Collection.objects.order_by('upload_date')&nbsp; &nbsp; listasubscription = Subscription.objects.filter(user=request.user)&nbsp; &nbsp; a_list = [] #You would get something like: ['not exist', 'not exist', 'Ok', 'not exist', 'Ok','Ok','Ok'] which is what it was printed in your code&nbsp; &nbsp; for obj in listacolecao:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Subscription.objects.filter(user=request.user, collection=obj)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; except Subscription.DoesNotExist:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #print('not exist') I would substitute it for .append, to add each value to the list as a new item&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a_list.append('not exist')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #print('Ok')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a_list.append('Ok')&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;#Now you pass that variable and sending it to your template, so you can use it there.&nbsp; &nbsp; context = {&nbsp; &nbsp; 'a_list':a_list,&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return render(request, 'your_template_name.html', context)在你的 urls.py 中:from .views import select_collections #Importing your recently created viewurlpatterns = [&nbsp; &nbsp;path = ('the_url_where_you_want_it', select_collections, name="the_name_you_prefer" ),]现在在您的模板中:#As you have already sent those variables here you can use Django's template tags{% for each_obj in a_list %}&nbsp; &nbsp; <h3> {{each_obj }} </h3> #If you change each_obj for a_list, you would get a QuerySet (fancy word for a list), with all the items in the "a_list" variable.{% endfor %}这应该允许您在模板中单独查看列表中的每个项目。
随时随地看视频慕课网APP

相关分类

Python
我要回答