There are at least two possible answers:
a. Use two forms and place them in one view. Transfer the Data object first, then create the Photo object without transferring it to the database, assign the data attribute to the Data instance, and then call .save() on the Photo instance (example below).
C. Use the inline model form: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
[EDIT]
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()
Make sure your form uses: multipart/form-data as enctype, or request.FILES will be empty.
source share