Django - upload images with additional information

210 Views Asked by At

So let's say I have a blog website. And each blog consists of images. So, I want to sort the images depending on which blog they belong to. But when uploading, how do I automatically pass the blog id with the image?

I have my model like this:

class Blog(models.Model):
    name = models.CharField()
    blog = models.CharField()

class Photo(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    file = models.FileField(upload_to=get_upload_path)

My forms.py looks like:

class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = ('file', 'blog')

You see in the fields there is 'blog'. How do I actually pass the blog id there?

Currently, my html for upload page is like this:

<div style="margin-bottom: 20px;">
    <button type="button" class="btn btn-primary js-upload-photos">
     <input id="fileupload" type="file" name="file" multiple
                   style="display: none;"
                   data-url="{% url 'blog' blog.id %}"
                   data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
</div>

Actually this way of uploading images is taken from this great article by Vitor Freitas

Now, I am wanting to pass the blog id to the template through views.py with context which I have done. But how do I save that and pass that with the images I upload?

the views.py looks like:

class BlogDetailView(View):

    def get(self, request,**kwargs):
        page = get_object_or_404(Page, pk=self.kwargs['pk'])
        context = {'page':page}

        return render(self.request, 'blog.html', context=context)


    def post(self, request, **kwargs):
        form = PhotoForm(self.request.POST, self.request.FILES)
        if form.is_valid():
            photo = form.save()
            data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
        else:
            data = {'is_valid': False}
        return JsonResponse(data)

So how do I associate an image with a blog when uploading?

Any help will be much much appreciated.

2

There are 2 best solutions below

0
On BEST ANSWER

Aight, so I solved my problem like this:

I kept the form just like it is. And in the html, I did nothing for the blog id. Rather, in views.py, I copied my post request like this:

    stuff = request.POST.copy()
    stuff['blog'] = blog.id

Then, I created the form with 'stuff' like this: form = PhotoForm(stuff, self.request.FILES)

And then did validation.

Doing like so, my problem got solved like a charm as I am now passing blog id with my photo.

0
On

Why don't you just pass in the file in your form like this:

if form.is_valid():
    photo = form.save(commit=False)
    photo.file = request.FILES['file']
    photo.save()