1

Rather than using Django admin, I wanted to make my own images upload on my site at 127.0.0.1/upload

Now, when I upload an image through the admin, it works fine. But when I upload though my own image, it's not uploading (and not to the correct path).

template

<form action="{% url 'app:publish' %}" method="post">
     {% csrf_token %}
     <input type="file" name="image_upload" accept="image/*" />
     <input type="submit" />
</form>

views.py

def publish(request):
    image = request.POST.get('image_upload', '')
    photo = Photo(image=image)
    photo.save()
    return HttpResponseRedirect('/')

models.py

def generate_path(self, filename):
    url = "%s/%s" % (self.college.name, filename)
    return url

class Photo(models.Model):
    image = models.ImageField(upload_to=generate_path, default="buildingimages/default.png")

This is was I usually do for text based fields, but I'm assuming files work differently, and that's why this is not working?

The object shows up in my admin after I try my upload, but the image itself doesn't seem to upload nor go to the right directory.

So the generate_path works totally fine when I upload through the admin, but through my own publish view, it seems to upload to /media/ and then it says image does not exist?

Any idea what I'm doing wrong

James Mitchell
  • 2,387
  • 4
  • 29
  • 59
  • Possible duplicate of [Django Image Uploading - Uploads do not work](http://stackoverflow.com/questions/41274700/django-image-uploading-uploads-do-not-work) – Anonymous Mar 17 '17 at 06:51

1 Answers1

1

Uploaded files are stored in request.FILES, not in request.POST.

Domen Blenkuš
  • 2,182
  • 1
  • 21
  • 29
  • So would it be request.FILES.get? I tried that and now the image is not uploaded at all. – James Mitchell Mar 17 '17 at 03:29
  • 1
    Yes, is your form of type `multipart/form-data`? You have a lot of tutorials on how to upload images with django, i.e. https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html – Domen Blenkuš Mar 17 '17 at 03:56