简体   繁体   中英

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. 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). In the terminal, it appears as

Query set Pic: Pic 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.

put parentheses after ImageForm and add request.POST in ImageForm if it is Post request.


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 .

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. try this in your template <img src="{{pic.picture.url}}">

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