2016-11-14 41 views
0
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> 
+0

你需要在這裏發佈你的表格來獲取幫助 – YPCrumble

+1

你如何選擇你需要的新文章'Inspectionfile'? –

+0

這是從索引模板完成的,因爲它通過主鍵進入特定文件。所以,當你點擊一個文件,它會轉到一個表格頁面,但帖子根本不連接到這個文件,這是我的問題 –

回答

0

嗯,我想你需要重寫你的createposts視圖post方法:

def post(self, request, *args, **kwargs): 
    current_inspectionfile = Inspectionfile.objects.get(pk= 
         #enter id of current file. If id is 
         #parameter in url then use self.kwargs['file_id'], 
         #where file_id is name of parameter in url 
        ) 
    new_post = posts.objects.create(inspectionfile=current_inspectionfile, 
         #and arguments from the form 
        ) 
    return new_post 

而且題外話:Python中的類名通常以單數形式在CamelCase中調用。所以class Post(models.Model)class CreatePost(CreateView):

+0

謝謝,這是有道理的。但是當你說表單參數時,你會發現我沒有一個實際的form.py,有沒有辦法從模板中獲取帖子屬性。 –

+0

@IshanSubedi檢查[this](http://stackoverflow.com/questions/11336548/django-taking-values-from-post-request)。而'形式'是指你的模板中的表單。 –

+0

你知道爲什麼我不斷收到:'posts'對象沒有屬性'get'錯誤。 url.py似乎很好。是否因爲我們正在創建一個新對象new_post,並且它不知道該如何處理它? –