简体   繁体   中英

Django: Saving images uploaded through ImageField

I am trying to set up a webapp that accepts image uploads from a user, using ImageField, but I cant seem to figure out how to save the uploaded image. My media folder is empty even though there doesnt seem to be any errors.

Went through a lot of tutorials to no avail. I get the basic concept, create a form, model, set media in settings.py, handle upload in views, and I am getting a working view with a image upload form, but uploading an image does not save.

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py

urlpatterns = [
    path('embed/', embed, name = 'embed'),
    path('success', success, name = 'success'), 
]


if settings.DEBUG: 
        urlpatterns += static(settings.MEDIA_URL, 
                              document_root=settings.MEDIA_ROOT) 

forms.py

class imguploadform(forms.ModelForm):
    class Meta:
        model = imgupload
        fields = ['title', 'image']

models.py

class imgupload(models.Model):
    title = models.CharField(max_length = 20)
    image = models.ImageField(upload_to="media/images/", default = None)

    def __str__(self):
        return self.title

views.py

def embed(request):
    if request.method == 'POST':
        form = imguploadform(request.POST, request.FILES)

        if form.is_valid():
            newimg = imgupload(title=request.POST['title'], image=request.FILES['image'])
            newimg.save()
            return redirect('success')

    else:
        form = imguploadform()

    return render(request, 'webapp/imgupload.html', {'form' : form})

def success(request):
    return HttpResponse("Successfully uploaded")

imgupload.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Upload Image</title> 
</head> 
<body> 
    <form method = "post" enctype="multipart/form-data"> 
        {% csrf_token %} 
        {{ form.as_p }} 
        <button type="submit">Upload</button> 
    </form> 
</body> 
</html> 

Another thing to note, the admin panel does not show the image model

The following code worked at my machine whoes os system is ubuntu18 with newest django and pillow

models.py

class Imgupload(models.Model):
    title = models.CharField(max_length=20)
    image = models.ImageField(upload_to="images/", default=None)

    def __str__(self):
        return self.title

views.py

def embed(request):
    if request.method == "POST":
        form = Imguploadform(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect("success")
    else:
        form = Imguploadform()
    img = Imgupload.objects.last()
    return render(request, "webapp/imgupload.html", {"form": form, "img": img})


def success(request):
    return HttpResponse("Successfully uploaded")

imgupload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Image</title>
</head>
<body>
    <form method = "post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>

    {% if img %}
    Image uploaded latest:
    <img src="{{ img.image.url }}">
    {% endif %}
</body>
</html>

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