简体   繁体   English

如何将图像上传到 Django

[英]How to Upload an Image to Django

I have spent over three days on this.我在这上面花了三天多的时间。 It appears that something saved to the db, but when I try to access it in the template, I can only get the object of the db.似乎有些东西保存到了数据库,但是当我尝试在模板中访问它时,我只能得到数据库的 object。 I can not access it.我无法访问它。 I believe it was not saved successfully because I don't see a media folder where it would be saved.我相信它没有成功保存,因为我没有看到将保存它的媒体文件夹。 This is what I have so far.这就是我到目前为止所拥有的。

# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/' 
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# forms.py
from .models import Pic
from django import forms
class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]
# models.py
class Pic(models.Model):
    picture = models.ImageField(upload_to = 'media/', default = 'media/None/no-img.jpg', null=True, blank= True)
# views.py
def upload(request):
    form = ImageForm
    context = {}
    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    if request.method == 'POST':
        # .is_valid checks the models parameters via forms method
        form = ImageForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            print("succesful uploaded image")
            return redirect("/dashboard")
        else:
            print("Not a valid input from form....")
            messages.error(request,"Not a valid input")
    return redirect("/dashboard")
<!-- dashboard.html -->
<form rule="form" class="border border--secondary" method="POST" action="/manageFile" enctype="multipart/form-data">
    {% csrf_token%}
    <input type="file" name = "update">
    <input type = "submit">
</form>
{% if pictures %}
    {% for pic in pictures%}
        <img src="{{pic}}" alt="{{pic}}">
    {% endfor %}
{% endif%}

In the template, it appears as Pic object(1).在模板中,它显示为 Pic 对象 (1)。 In the terminal, it appears as在终端中,它显示为

Query set Pic: Pic object (1)查询集图:图object(1)

Here's what I render to the template.这是我渲染到模板的内容。

def dash(request):
    try:
        _id = request.session['client']['id']
    except:
        return redirect("/loginPg")

    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    print("its right here")
    theUploads = Pic.objects.all()
    print("This image object -", theUploads)

    content = {
        "title" : userBio.title,
        "qA" : userBio.quoteA,
        "qB" : userBio.quoteB,
        "desc" : userBio.desc,
        "authorA" : userBio.authorA,
        "authorB" : userBio.authorB,
        "pictures" : theUploads
    }

    return render(request, "GoEnigma/dashboard.html", content)
# urls.py
from django.conf.urls.static import static
from django.conf import settings
# urls []
if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This was hard to spot, because you render the form field yourself:这很难发现,因为您自己渲染表单域:

class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]
    <input type="file" name = "update">

So the name of the file field is update, not picture.所以文件字段的名称是更新,而不是图片。 Change that to picture and it should work, though it's much better to use django to render the form, so you don't mistakes like this and changes to the form get propagated to the html.将其更改为图片,它应该可以工作,尽管使用 django 渲染表单要好得多,因此您不会犯这样的错误,并且对表单的更改会传播到 html。

put parentheses after ImageForm and add request.POST in ImageForm if it is Post request.在 ImageForm 后面加上括号,如果是 Post 请求,则在 ImageForm 中添加 request.POST。


def upload:
  form = ImageForm()
  if request.method == 'POST':
    # .is_valid checks the models parameters via forms method
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        print("succesful uploaded image")
        return redirect("/dashboard")
    else:
        print("Not a valid input from form....")
        messages.error(request,"Not a valid input")
return redirect("/dashboard")

Also check maybe you haven't added url path for serving media files so add these following lines in urls.py file of main project .还要检查您是否没有添加 url 路径来提供媒体文件,因此在main projecturls.py文件中添加以下几行。

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
  # ..... all regular paths
] 
if setting.DEBUG: # if true
  urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Check official documents here 在这里查看官方文件

If the picture is being saved in the database than the error is with rendering the template.如果图片被保存在数据库中,则错误在于渲染模板。 To render the images in template you need to get the {{model_class.model_fields.url}} so in your case the class is pic, the field is picture.要在模板中渲染图像,您需要获取 {{model_class.model_fields.url}},因此在您的情况下,class 是图片,字段是图片。 try this in your template <img src="{{pic.picture.url}}">在你的模板中试试这个<img src="{{pic.picture.url}}">

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

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