user2096122
user2096122

Reputation: 45

Models form with foreign key

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

How to add to this form photo upload?

Upvotes: 4

Views: 145

Answers (2)

Brandon Taylor
Brandon Taylor

Reputation: 34553

There are at least two possible answers:

A. Use two forms and post them to the same view. Persist the Data object first, then create the Photo object without committing it to the database, assign the data attribute to the data instance, and then call .save() on the photo instance (example provided below).

B. Use an inline model formset: 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()
            # do something else here, like a redirect to another view.
    return render(request, 'your-template.html',
        {'data_form': data_form, 'photo_form': photo_form})

Make sure your form is using: multipart/form-data as the enctype, or request.FILES will be empty.

Upvotes: 3

Zulu
Zulu

Reputation: 9265

Add manualy ImageField to Form and overide save method to create a photo :

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

Upvotes: 1

Related Questions