Django 如何正确上传图片到表单?
Django How to properly upload image to form?
这是我与表单关联的代码:
型号
class Date(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=64, null=True)
class Photo(models.Model):
date = models.ForeignKey('Date', on_delete=models.CASCADE)
image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/')
# form
class DateForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = Date
exclude = ('user',)
# view
class CreateDateView(LoginRequiredMixin, CreateView):
template_name = 'app/date/form.html'
form_class = DateForm
def form_valid(self, form):
form.instance.user = self.request.user
form.save() # by the way why do I save this form? Is it okay to save it in
form_valid method?
photos = self.request.FILES.getlist('image')
for photo in photos:
Photo.objects.create(image=photo)
return super().form_valid(form)
问题是如果需要 日期 模型 ID,如何保存照片对象。它引发 NOT NULL 约束失败:app_photo.date_id
据我所知,我必须写这样的东西:
Photo.objects.create(date=date_from_the_form, image=photo)
但是如何从 Date 模型中获取 pk 呢?希望您理解我的问题,如果有任何问题,请随时在评论部分将其写下来。提前致谢!
Error
当您调用 form.save()
时,它 returns 模型实例,这样您就可以像这样从中获取实例
def form_valid(self, form):
form.instance.user = self.request.user
date_instance = form.save()
photos = self.request.FILES.getlist('image')
for photo in photos:
Photo.objects.create(date=date_instance, image=photo)
return super().form_valid(form)
这是我与表单关联的代码:
型号
class Date(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=64, null=True)
class Photo(models.Model):
date = models.ForeignKey('Date', on_delete=models.CASCADE)
image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/')
# form
class DateForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = Date
exclude = ('user',)
# view
class CreateDateView(LoginRequiredMixin, CreateView):
template_name = 'app/date/form.html'
form_class = DateForm
def form_valid(self, form):
form.instance.user = self.request.user
form.save() # by the way why do I save this form? Is it okay to save it in
form_valid method?
photos = self.request.FILES.getlist('image')
for photo in photos:
Photo.objects.create(image=photo)
return super().form_valid(form)
问题是如果需要 日期 模型 ID,如何保存照片对象。它引发 NOT NULL 约束失败:app_photo.date_id
据我所知,我必须写这样的东西:
Photo.objects.create(date=date_from_the_form, image=photo)
但是如何从 Date 模型中获取 pk 呢?希望您理解我的问题,如果有任何问题,请随时在评论部分将其写下来。提前致谢!
Error
当您调用 form.save()
时,它 returns 模型实例,这样您就可以像这样从中获取实例
def form_valid(self, form):
form.instance.user = self.request.user
date_instance = form.save()
photos = self.request.FILES.getlist('image')
for photo in photos:
Photo.objects.create(date=date_instance, image=photo)
return super().form_valid(form)