简体   繁体   English

Django:保存通过ImageField上传的图像

[英]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. 我试图建立一个使用ImageField接受用户上传图像的webapp,但是我似乎无法弄清楚如何保存上传的图像。 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中设置了媒体,在视图中处理了上传,并且正在使用图像上传表单获得一个工作视图,但是上传图像并不能保存。

settings.py settings.py

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

urls.py 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 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 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 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 以下代码在我的机器whoes os系统上工作,是ubuntu18,带有最新的django和pillow

models.py 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 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 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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