Django,链接到数据库中的对象

2024-09-30 18:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个django测试项目,其中包含一个名为customers的表的postgresql数据库。 在/customers/中呈现所有客户很好,但我正在寻找一种方式来呈现单个客户,如下所示:/customer/{{{customer.id}。不太确定我在找什么,有没有人能帮我找到正确的文档或其他什么

非常感谢

列出所有客户并在单击div时打开给定客户:

<div class="container">
    {% for customerz in custs_all %}
    <br>
    <div class="row shadow-sm d-flex w-1000 justify-content-between" onclick="location.href='/customers/{{customerz.id}}';" style="cursor: pointer;">
      <div class="col-xl-4"><h5 class="mb-1">{{ customerz.name }}</h5></div>
      <div class="col-xl-4">Contact person: {{ customerz.contactperson }}</div>
      <div class="col-xl-4">Email: {{ customerz.email }}</div>
      <div class="col-xl-4">Active: <span class="badge badge-light">{{ customerz.active }}</span></div>
    </div>
    {% endfor %}
</div>

这就是我不明白的,我需要读什么文件才能让它正常工作

onclick="location.href='/customers/{{customerz.id}}';"

我不知道我在找什么,所以很难在这里提出正确的问题。。对不起


Tags: badgedivid客户collocationcustomerclass
3条回答
        The previous answer was correct, in action doe ; you could do something like this :
     
    -- you could grab the customer id through request.form; if you use form within your table; i guess this is the best approach to do so.
    -- than you can set something with (url_for), and give it a parameter as {{ customer.id}} , within your .html . 
    -- than handle the logic when returning this object.
    
    You can check this project, go through it , you might find something similar to this : 
     [https://github.com/Nouamanezh909/BLog_repo][1]

我想你在找this。您可以在URL请求中传递ID,并使用它从数据库中获取所需的对象

views.py

def customer_detail(request, pk):
  customer = get_object_or_404(Customer, id=pk)
  return render (request, template, {'customer': customer}

这里pk是主键,所以您从模型客户(或您所命名的任何客户)中获取客户

urls.py

path('customer/<int:pk>/', views.customer_detail, name='customer-detail')

在客户列表模板中,您可以添加链接以添加客户详细信息模板,如<a href="{% 'customer-detail' cutomer.pk %}"> cutomer detail </a>

相关问题 更多 >