亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Django 后端循環到前端列表

Django 后端循環到前端列表

狐的傳說 2023-05-16 09:47:48
很抱歉這個問題,但我是 Django 的初學者,我找不到任何像這種情況這樣的話題。這是代碼:views.pydef 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 existnot existOknot existOkOkOkOk我知道那不是列表,但我需要將其結果放入模板中。我怎樣才能做到這一點?
查看完整描述

1 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

如果你只是想要你在那里擁有的相同但打印在你擁有的模板中,(以我的謙虛和初學者的觀點)你需要稍微修改你的視圖,創建一個你想要顯示它的模板并將 url 修改為在該模板中加載視圖,例如:


查看.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', 'not exist', 'Ok','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 %}


這應該允許您在模板中單獨查看列表中的每個項目。


查看完整回答
反對 回復 2023-05-16
  • 1 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號