Django How to properly upload image to form?


This is my code associated with the form:


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 # 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:
        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!



When you call 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 = 
    photos = self.request.FILES.getlist('image')
    for photo in photos:
       Photo.objects.create(date=date_instance, image=photo)
    return super().form_valid(form)

Answered By – Ankit Tiwari

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published