class Data(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
class Photo(models.Model):
photo = models.ImageField(upload_to='img')
data = models.ForeignKey(Data)
forms.py:
class DataForm(ModelForm):
class Meta:
model = Data
如何添加到此表单照片上传?
答案 0 :(得分:3)
至少有两种可能的答案:
一个。使用两个表单并将它们发布到同一视图。首先保留Data
对象,然后创建Photo
对象而不将其提交到数据库,将数据属性分配给data
实例,然后在.save()
上调用photo
{1}}实例(下面提供的示例)。
B中。使用内嵌模型formset:https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
[编辑]
class Data(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
class Photo(models.Model):
photo = models.ImageField(upload_to='img')
data = models.ForeignKey(Data)
class DataForm(forms.ModelForm):
class Meta:
model = Data
class PhotoForm(forms.ModelForm):
class Meta:
model = Photo
exclude = ('data',)
def your_view(request):
data_form = DataForm(request.POST or None)
photo_form = PhotoForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if data_form.is_valid() and photo_form.is_valid():
data = data_form.save()
photo = photo_form.save(commit=False)
photo.data = data
photo.save()
# do something else here, like a redirect to another view.
return render(request, 'your-template.html',
{'data_form': data_form, 'photo_form': photo_form})
确保您的表单正在使用:multipart/form-data
作为enctype,或request.FILES
将为空。
答案 1 :(得分:1)
手动ImageField
添加到表单并覆盖save
方法以创建照片:
class DataForm(ModelForm):
class Meta:
model = Data
photo = forms.ImageField()
def save(self, *arg, **kwargs):
data = super(DataForm, self).save(*arg, **kwargs)
if 'photo' in self.data :
Photo.objects.create(
photo=self.data['photo'],
data=data
)
return data