Home > database >  Django How to properly upload image to form?
Django How to properly upload image to form?

Time:05-13

This is my code associated with the form:

models

class Date(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=64, null=True)


class Photo(models.Model):
    date = models.ForeignKey('Date', on_delete=models.CASCADE)
    image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/')

# form

class DateForm(forms.ModelForm):
    image = forms.ImageField()
    class Meta:
        model = Date
        exclude = ('user',)

# view

class CreateDateView(LoginRequiredMixin, CreateView):
    template_name = 'app/date/form.html'
    form_class = DateForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.save() # by the way why do I save this form? Is it okay to save it in 
form_valid method?
        photos = self.request.FILES.getlist('image')
        for photo in photos:
            Photo.objects.create(image=photo)
        return super().form_valid(form)

The issue is how to save Photo objects if it requires a Date model id. It raises NOT NULL constraint failed: app_photo.date_id As I understand I have to write something like:

Photo.objects.create(date=date_from_the_form, image=photo)

But how to get the pk from the Date model? Hope you understand my problem, if any questions don't hesitate to write them down below in the comments section. Thanks in advance!

Error

CodePudding user response:

When you call form.save() it returns model instance so you can get instance from it like this

def form_valid(self, form):
    form.instance.user = self.request.user
    date_instance = form.save() 
    photos = self.request.FILES.getlist('image')
    for photo in photos:
       Photo.objects.create(date=date_instance, image=photo)
    return super().form_valid(form)
  • Related