简体   繁体   English

图片未使用 django 从数据库加载到网页上

[英]images not loading on webpage from database using django

i have made a library web app.我制作了一个图书馆 web 应用程序。 i am trying to make a search for searching the books from database.all other information such as title is showing except the image.below is the screenshot enter image description here我正在尝试搜索从数据库中搜索书籍。除图像外,所有其他信息(例如标题)均显示。以下是屏幕截图,在此处输入图像描述

below is my search.html下面是我的搜索。html


    {% extends 'bookslib/base.html' %}
    {% block body_block %}
    {% load static %}
    {% if books %}
    {% for book in books %}
           <div class="books">
        <div class="book">
            <img src="{{ book.imagefile.url }}" height="250px" width="200px">
        <p>{{ book.title }}</p>
        </div>
    </div>    

{% endfor %}
{% endif %}
{% endblock %}

below is search view:以下是搜索视图:

enter code here
 def search(request):

    if request.method == "POST":
        query = request.POST.get('query')
        if query:
            books = Book.objects.filter(Q(title__icontains=query) | Q(author__name__icontains=query))
            if books:
                return render(request, 'bookslib/search.html', {'books':books})
        else:
            return redirect('bookslib/home.html')
    return redirect('bookslib/home.html')   

i have added this path to my main project's urls.py我已将此路径添加到我的主项目的 urls.py

enter code here
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

my images are in media/images/ media directory is in directory where my project and app is stored.我的图像位于 media/images/ 媒体目录中,位于存储我的项目和应用程序的目录中。 kindly help me.请帮助我。 if you need another information please let me know.如果您需要其他信息,请告诉我。 thank you in advance.先感谢您。

Try putting your files in the static folder, and setting this on setting.py.尝试将您的文件放在 static 文件夹中,并在 setting.py 上进行设置。

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')

if DEBUG == False:
    STATIC_URL = '/static/'
    #STATICFILES_DIRS = [STATIC_DIR,"/var/www/static"]
    STATIC_ROOT = os.path.join(BASE_DIR,"static")
    MEDIA_ROOT = MEDIA_DIR
    MEDIA_URL = '/media/'

else:
    MEDIA_URL = '/media/'
    STATIC_URL = '/static/'

Then run python manage.py collectstatic Your static files will all be moved to the /static folder as defined in settings.py.然后运行 python manage.py collectstatic 您的 static 文件将全部移动到 settings.py 中定义的 /static 文件夹。 To reference your image you will use the path to the image in the static folder: <img src="/static/name_of_your_image" height="250px" width="200px">要引用您的图像,您将使用 static 文件夹中的图像路径: <img src="/static/name_of_your_image" height="250px" width="200px">

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

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