【问题标题】:Django passing a foreign key from ListView to a DetailviewDjango 将外键从 ListView 传递到 Detailview
【发布时间】:2017-07-27 03:53:58
【问题描述】:

关于 Django 中的视图,我不太了解。我的站点将有一张桌子,桌子上有不同的工作或负载。这称为负载板。这引用了一个名为 Loadboard_table 的数据库表。 Loadboard_table 包含数据库中 Company_table 的外键。此数据库表包含分配此工作/负载的公司以及有关公司的其他信息。

目标是让用户点击加载板上的任何一行,这会将用户带到公司的“详细信息”页面。我已经在下面显示了代码的精简部分,以免使问题变得臃肿。

索引上的表格行项目

<!-- this is where I grab my Company table foreign key by clicking on one of the loadboard items -->
<td>
 <a href="{% url 'loadboard:detail' item.CompanyName_id %}">   {{item.CompanyName}}</a>
</td>

urls.py

urlpatterns = [
# /loadboard/
url(r'^$', views.IndexView.as_view(), name='index'),

# /loadboard/71/
#note this is where I am trying to pass the foreign key to
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
]

views.py

from django.views import generic
from .models import Company_table, Loadboard_table


class IndexView(generic.ListView):
    template_name = 'loadboard/index.html' 
    context_object_name = 'all_loadboard' 

    def get_queryset(self):
        return Loadboard_table.objects.all() 

class DetailView(generic.DetailView):
    model = Company_table
    template_name = 'loadboard/detail.html'

detail.html

<!-- I want this detail page to show the Company that the loadboard's foreign key references -->
<head>
    <title>{% block title %}{{Company_table.CompanyName}}'s loadboard{% endblock %}</title>
</head>

非常感谢您的帮助!

【问题讨论】:

    标签: python django-models sqlite django-templates django-views


    【解决方案1】:

    我找到了一种无需使用 DetailView 类即可达到目标的方法。我只是创建了一个函数来处理 HTTP 请求并从 url 中获取 CompanyId。我认为 DetailsView 类用于更具体的情况。

    当用户点击时:

    <td>
    <a href="{% url 'loadboard:detail' item.CompanyName_id %}">{{item.CompanyName}}</a>
    </td>
    

    然后它会在 urls.py 上触发这个 URL 模式:

    url(r'^([0-9]+)/$', views.ViewCompanyDetails, name='detail')
    

    在views.py上使用函数:

    def ViewCompanyDetails(request, CompanyId):
        CompanyObject = Company_table.objects.get(id = CompanyId)
        context = {'Company': CompanyObject}
        return render(request, 'loadboard/detail.html', context)
    

    这实现了我的目标,即尝试从用户单击表格的位置传递公司 ID,并将其一直传递到视图页面并获取该 HTML 页面。

    我可能对泛型模型中的 DetailsView 类有误,它对主键过于具体,但有人可以纠正我。

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 1970-01-01
      • 2012-12-15
      • 2018-05-28
      • 2019-10-02
      • 2023-04-09
      • 2016-08-07
      • 2017-09-18
      • 1970-01-01
      相关资源
      最近更新 更多