![](/img/trans.png)
[英]Django - Create or Update reverse foreign key object from parents 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.