如何保存我的ForeignKey的属性?

时间:2019-06-25 09:16:25

标签: django

我正在尝试创建一个视图,允许用户在“我的课程”模型中上载文档。但是,在上载文档时,我无法保存正在提交表单的实例。当我访问管理页面时,我的ForeignKey字段保留为空。

这是供用户提交其文档的views.py:

class UploadLessonView(CreateView):
model = Lesson
fields = ['title', 'file']  
template_name = 'store/upload_lesson.html'
success_url = '../'

def form_valid(self, form):
    form.instance.author = self.request.user
    return super(UploadLessonView, self).form_valid(form)

这是我的孩子模型的models.py:

class Lesson(models.Model):
title = models.CharField(max_length=100)
file = models.FileField(upload_to="lesson/pdf")
date_posted = models.DateTimeField(default=timezone.now)
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('lesson_upload', kwargs={'pk': self.pk})

对于我的父模型:

class Post(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(default = 'default0.jpg', upload_to='course_image/')
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=6)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.IntegerField(default = 0)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('post-detail', kwargs={'pk' : self.pk})

提交文档时,“发帖字段”为空。

1 个答案:

答案 0 :(得分:0)

您没有使用视图在Post中设置Lesson对象。因此,您可以通过两种方式对其进行修复。

一种方法是通过url发送,例如:

# url
url('lesson/<int:post_id>/create/', UploadLessionView.as_view())

并在视图中使用post_id的值:

class UploadLessonView(CreateView):
    model = Lesson
    fields = ['title', 'file']  
    template_name = 'store/upload_lesson.html'
    success_url = '../'

    def form_valid(self, form):
        form.instance.post = get_object_or_404(Post, pk=self.kwargs.get('post_id'))
        return super(UploadLessonView, self).form_valid(form)

两个,您可以在字段中添加post

class UploadLessonView(CreateView):
    model = Lesson
    fields = ['title', 'file', 'post']  # <-- Here
    template_name = 'store/upload_lesson.html'