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

我知道这不是一个列表,但是我需要将其结果放入模板中。我该怎么办?

谢谢

解决方法

如果您只想拥有那里的东西,但要打印在您拥有的模板中(以我的谦逊和初学者的观点),则需要修改一点视图,在要显示它的模板上创建并修改在该模板中加载视图的网址,例如:

View.py的更改:

def select_collections(request):
    listacolecao = Collection.objects.order_by('upload_date')
    listasubscription = Subscription.objects.filter(user=request.user)
    a_list = [] #You would get something like: ['not exist','not exist','Ok','Ok'] which is what it was printed in your code
    for obj in listacolecao:
                try:
                    Subscription.objects.filter(user=request.user,collection=obj)
                except Subscription.DoesNotExist:
                    #print('not exist') I would substitute it for .append,to add each value to the list as a new item
                    a_list.append('not exist')
                else:
                    #print('Ok')
                    a_list.append('Ok')
   
    
#Now you pass that variable and sending it to your template,so you can use it there.
    context = {
    'a_list':a_list,}
    
    return render(request,'your_template_name.html',context)

在您的urls.py中:

from .views import select_collections #Importing your recently created view

urlpatterns = [
   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 %}
    <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 %}

这应该允许您在模板中单独查看列表的每个项目。