图片未在Django中上传

时间:2018-10-19 08:15:52

标签: django python-3.x

我已在管理门户中上传了图片 但它不是在html模板中呈现 我该如何解决? 以下是源代码! models.py

from django.db import models
from django.contrib.auth import get_user_model
from PIL import Image

class Question(models.Model):
    question_relation=models.ForeignKey('Answer',related_name='ques',on_delete=models.CASCADE)
    question_image=models.ImageField(upload_to='levels/media/')
    text=models.TextField(blank=True,max_length=100)

    def __str__(self):
        return str(self.question_relation)

html文件

 <div style="margin-left:35%;margin-right:35%">
       <img src="{{Question.question_image.url}}" alt="">
            <form class="post-form" method="post">
            {%csrf_token%}
            {{form.as_p}}
            <button type="submit" class="save btn btn-default">Submit</button>
            </form>
            <script>var editor=new MediumEditor('.editable');</script>

        </div>

我已将它们包含在我的urls.py

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

在检查img src中的inspect元素时,它显示为(未知)。 我不知道为什么它无法获取图片的网址

settings.py

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

views.py

from django.shortcuts import render,redirect,get_object_or_404
from django.views.generic import *
from . import models
from django import forms
from .forms import CheckAnswer
from django.contrib.auth.decorators import login_required
from .models import Question

# Create your views here.
@login_required
def Arena1(request):
    if request.method=='POST':
        form = CheckAnswer(request.POST)
        if form.is_valid():
            return redirect('thanks')
    else:
        form=CheckAnswer()
    args={'form':form}
    return render(request,'levels/arena1.html',args)

1 个答案:

答案 0 :(得分:1)

您忘记设置{ Senior: 100, Adult: 90, Child: 35, Infant: 25 } { Senior: 100, Adult: 90, Child: 35, Infant: 25 }

将表单更新为-

enctype="multipart/form-data"

编写客户端代码时,您需要知道的是在表单包含任何元素时使用multipart / form-data。如果想知道为什么请参阅here