在Djang中如何在基于类的视图中链接外键

2024-10-02 20:41:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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(外键)链接。我希望用户被链接而不必选择。下面是我的模型。所以我想把每个帖子链接到一个特定的检查文件。在

^{pr2}$

表单是一个简单的模板:

<form class = "form_horizontal" action = "" method = "post">
    {% csrf_token %}
    {{form.as_p}}
    <button type="submit">Submit</button>
</form>

Tags: nameform表单model链接htmlbuttontemplate
1条回答
网友
1楼 · 发布于 2024-10-02 20:41:31

我认为您需要重写post视图中的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)和{}

相关问题 更多 >