繁体   English   中英

Django将外键从ListView传递到Detailview

[英]Django passing a foreign key from ListView to a Detailview

关于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>

非常感谢您的帮助!

我找到了一种无需使用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类,我可能是错的,它对于主键过于具体,但有人可以对此进行纠正。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM