class IndexView(generic.ListView):
template_name = "posts/index.html"
def get_queryset(self):
return Inspectionfile.objects.all()
class DetailView(generic.DetailView):
model = Inspectionfile
template_name = "posts/detail.html"
class createposts(CreateView):
model = posts
fields = ['title','comments']
通過createposts和使用表單我可以填充標題和註釋,但它們沒有與任何Inspectionfile(外鍵)鏈接。我希望用戶在沒有他們選擇的情況下進行鏈接。以下是我的模型。所以我想把每個帖子都鏈接到一個特定的檢查文件。如何在Django的基於類的視圖中鏈接外鍵
class Inspectionfile(models.Model):
document_upload = models.FileField()
document_type = models.CharField(max_length=10)
document_title = models.CharField(max_length=250)
document_check = models.CharField(max_length=250)
def __str__(self):
return (self.document_title + self.document_type)
class posts(models.Model):
inspectionfile = models.ForeignKey(Inspectionfile, on_delete=models.CASCADE, default=1)
title = models.CharField(max_length=120)
comments = models.TextField()
flag = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('posts_form', kwargs={'pk': self.pk})
def __str__(self):
return self.title
形式是一個簡單的模板:
<form class = "form_horizontal" action = "" method = "post">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Submit</button>
</form>
你需要在這裏發佈你的表格來獲取幫助 – YPCrumble
你如何選擇你需要的新文章'Inspectionfile'? –
這是從索引模板完成的,因爲它通過主鍵進入特定文件。所以,當你點擊一個文件,它會轉到一個表格頁面,但帖子根本不連接到這個文件,這是我的問題 –