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

时间:2016-11-14 19:07:06

标签: python django django-views django-generic-views

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']

通过创建帖子和使用表单我可以填充标题和注释,但它们没有与任何Inspectionfile(外键)链接。我希望用户无需选择即可进行链接。以下是我的模型。所以我想将每个帖子链接到特定的检查文件。

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>

1 个答案:

答案 0 :(得分:0)

我认为您需要在post视图中覆盖createposts方法:

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

Off-topic:python中的类名通常以单数形式在CamelCase中调用。所以class Post(models.Model)class CreatePost(CreateView):