Django for循环在一个模板页面上工作,但在其他地方消失了?

wi3ka0sx  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(151)

我写了一个Django for循环,它迭代Supplier模型的每个示例,并在导航栏中呈现每个示例,但由于某些原因,它只在我的一个模板上输出,而不是主页面。

<ul class="nav-drop">
    {% for supplier in suppliers %}
    <li>
        <a href="{% url 'supplier' pk=supplier.pk %}">{{ supplier.name }}</a>
    </li>
    {% endfor %}
</ul>

下面是我的views.py文件:
x一个一个一个一个x一个一个二个x
以及所讨论的模型:

class Supplier(models.Model):
    name = models.CharField(max_length=200, blank=True, null=True)
    logo_image = models.ImageField(null=True, blank=True, upload_to='models/',
    default="models/default.jpg") 
    marketing_image = models.ImageField(null=True, blank=True, upload_to='models/', 
    default="models/default.jpg")
    description = models.TextField(blank=True, null=True)
    short_description = models.TextField(max_length=200, blank=True, null=True)
    social_facebook = models.CharField(max_length=200, blank=True, null=True)
    social_twitter = models.CharField(max_length=200, blank=True, null=True)
    social_instagram = models.CharField(max_length=200, blank=True, null=True)
    social_youtube = models.CharField(max_length=200, blank=True, null=True)
    social_linkedin = models.CharField(max_length=200, blank=True, null=True)
    social_website = models.CharField(max_length=200, blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)
    id = models.UUIDField(default=uuid.uuid4, unique=True,
                          primary_key=True, editable=False)

我已经试了几个小时了,但不幸的是,我无法想出一个解决办法

alen0pnh

alen0pnh1#

看起来您只在其中一个视图中传递供应商列表。因此,一个视图有要呈现的内容,而另一个视图没有,基本的解决方案是在所有视图的上下文中添加供应商。

# Create your views here.
def suppliers(request):
    suppliers = Supplier.objects.all()

    context = {'suppliers': suppliers}
    return render(request, 'suppliers/suppliers.html', context)

def supplier(request, pk):
    suppliers = Supplier.objects.all()
    supplier = Supplier.objects.get(id=pk)

    context = {'supplier': supplier, 'suppliers': suppliers}
    return render(request, 'suppliers/supplier.html', context)

正如你所看到的,这违背了DRY原则,使你的代码变脏。一个可能的解决方案是创建一个视图,从你的base.html(你可能在其中包含了navbar)发送一个 AJAX :
base.html

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    </head>
    <header>
        {% include 'includes/navbar.html' %}
    </header>
    <body>
        {% block content%}
        
        {% endblock content%}
    </body>
    <footer>
        <script>
            fetch("{% url 'core:supplier_list_ajax' %}")
            .then((response) => response.json())
            .then((data) => {
                let e = document.getElementById("second-choice");
                for (let key in data['suppliers']){
                    id = data['suppliers'][key].id
                    name = data['suppliers'][key].name
                    url = `/supplier/${id}/`
                    e.innerHTML += `<a href="${url}">${name}</a><br>`
                }
            });
        </script>
    </footer>
</html>

navbar.html

<div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
      Normal Dropdown
    </button>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
        {% for supplier in suppliers %}
        <li>
            <a href="{% url 'core:supplier' pk=supplier.pk %}">{{ supplier.name }}</a>
        </li>
        {% endfor %}
    </ul>

    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
      AJAX Dropdown
    </button>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
      <li id="second-choice">
      </li>
    </ul>
  </div>

views.py

from django.shortcuts import render
from django.http import JsonResponse

from .models import Supplier

def suppliers(request):
    suppliers = Supplier.objects.all()

    context = {'suppliers': suppliers}
    return render(request, 'suppliers/suppliers.html', context)

def supplier(request, pk):
    supplier = Supplier.objects.get(id=pk)

    context = {'supplier': supplier}
    return render(request, 'suppliers/supplier.html', context)

def supplier_list_ajax(request):
    suppliers = list(Supplier.objects.all().values('name','id'))
    return JsonResponse({'suppliers': suppliers})

urls.py

from django.urls import path
from core import views

app_name = 'core'

urlpatterns = [
    path('suppliers/', views.suppliers, name='suppliers'),
    path('supplier/<str:pk>/', views.supplier, name='supplier'),
    path('supplier/list/ajax/', views.supplier_list_ajax, name='supplier_list_ajax')
]

我保留了两个下拉菜单,因此您可以看到操作中的不同。

相关问题