至少有两种可能的答案:
A. 使用两个表单并将它们发布到同一个视图。首先持久化Data
对象,然后创建Photo
对象而不将其提交到数据库,将数据属性分配给data
实例,然后调用.save()
实例photo
(下面提供示例)。
B. 使用内联模型表单集: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
作为编码类型,否则request.FILES
将为空。