[Answer]-Display parent field on django forms

1👍

You can simply add an ImageFormField to the MascotForm and override the save method to create the Image instance also, like this:

class MascotForm(forms.ModelForm):
    image = forms.ImageField()

    class Meta:
        model = Mascot

    def save(self, commit=True):
        # mascot will have to save in this case, we don't pass commit
        mascot = super(MascotForm, self).save()
        image = Image.objects.create(mascot=mascot,
                                     image=self.cleaned_data.get('image'))
        return mascot

This would be one way. But a better way would be to have both forms in the view.
Create a ImageForm for the Image model and handle the save in the view:

    class ImageForm(forms.ModelForm):
        class Meta:
            model = Image
            fields = ('image',)

        def save(self, mascot, commit=True):
            image = super(ImageForm, self).save(commit=False)
            image.mascot = mascot
            if commit:
                image.save()
            return image

    def my_view(request):
        if request.method == 'POST':
            mascot_form = MascotForm(request.POST)
            image_form = ImageForm(request.POST, request.FILES)

            if mascot_form.is_valid() and image_form.is_valid():
                mascot = mascot_form.save()
                image = image_form.save(mascot)
                return redirect(....)
        else:
            mascot_form = MascotForm()
            image_form = ImageForm()
        return render(request, 'some_template.html', {
            'mascot_form': mascot_form,
            'image_form': image_form
        })

Leave a comment