简体   繁体   中英

Django saving an image that is a model field, works on /admin but not custom upload page

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

上传的文件都存储在request.FILES ,而不是在request.POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM