【问题标题】:Django generic.ListVIew: display list item's details on the same page (~ combine ListView and DetailView)Django generic.ListVIew:在同一页面上显示列表项的详细信息(~结合ListView和DetailView)
【发布时间】:2021-12-14 18:28:54
【问题描述】:

我想要的是在包含 ListView 的同一页面上显示单击的 ListView 项目的详细信息(粗略地说,将 generic.ListView 与 generic.DetailView 结合起来)。我所做的是:

generic.ListView 的联系人:

from .models import Contact
from django.views import generic

class ContactList(generic.ListView):
    model = Contact
    context_object_name = 'contacts'
    template_name = 'contacts/list.html'

contacts/list.html 模板包含一个 JS Fetch 请求 (GET) 以获取点击的项目:

{% block content %}
{% if contacts %}
    <ul>
    {% for contact in contacts %}
        <li><a id="{{ contact.id }}" onClick="showDetails(this.id)">{{ contact.first_name }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    No contacts. 
{% endif %}

<div id='contactDetail'></div>

<script type="text/javascript">
  function showDetails(contactId){
    console.log(contactId);
    fetch(`http://127.0.0.1:8080/contacts/${contactId}`, {
        headers: {
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
        },
    })
    .then(response => {
        // should 500 be processed?
        return response.json();
    })
    .then(data => {
        //Perform actions with the response data from the view
        window.onload = function() {
            // build html markup next
            document.getElementById("contactDetail").innerHTML= ...;
        } 
    })
  }
</script>
{% endblock content %}

处理这个 Fetch-GET 请求的 Django 视图是:

from django.shortcuts import get_object_or_404
from django.forms.models import model_to_dict

def contact_details(request, contact_id):
    contact = get_object_or_404(Contact, pk=contact_id)
    contact = {k: v for k, v in model_to_dict(contact).items() if v}
    return JsonResponse(contact)

方法对吗?

【问题讨论】:

    标签: django django-templates django-generic-views


    【解决方案1】:

    你的方式几乎没有问题。

    虽然是生产,但您应该使用pagination。 这样应该不会有太多数据,我认为最好将所有字段与列表一起返回,但首先隐藏额外的字段,然后在点击时取消隐藏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 2018-11-28
      相关资源
      最近更新 更多