Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django How to properly upload image to form?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading