簡體   English   中英

圖像未顯示在 django 中

[英]images are not showing in django

嗨,當我從我的管理員那里保存圖像時,它們會像這樣保存在項目目錄中 images/images/myimg.jpg .. 但是當我試圖像這樣在我的模板中顯示它們時

    <img src="{{About.image.url}}" alt="profile photo">

圖像不顯示.. 當我在 chrome 中檢查頁面時... 它顯示圖像來源未知..

     <img src="(unknown)" alt="profile photo">

請看文件..

設置.py

                         STATIC_URL = '/static/'
           STATICFILES_DIRS =[
                     os.path.join(BASE_DIR,'portfolio/static')
                                ]
             STATIC_ROOT = os.path.join(BASE_DIR,'media')

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

項目網址.py

         from django.contrib import admin
         from django.urls import path,include
         from django.conf import settings
         from django.conf.urls.static import static
        
           urlpatterns = [

          path('admin/', admin.site.urls),
         path('home/', include("home.urls")),
         path('blog/', include("blog.urls")),


             ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT )

有圖像的 model 在名為“home”的應用程序中

家庭應用的models.py

          from django.db import models
          import datetime
          # Create your models here.
            class About(models.Model):
                 image = models.ImageField(upload_to = 'images')
                 desc  = models.TextField()

家/views.py

            from django.shortcuts import render
             from home.models import *
            from django.views.generic import ListView

           # Create your views here.
           def index(request):
            abt = About.objects.all()
             return render(request,'home/index.html',{'abt': abt.first()})

         def Experience(request):
            Exp = Experience.objects.all()
             return render(request,'home/Experience.html',{'Exp': Exp})


           class MyView(ListView):
            context_object_name = 'name'
              template_name = 'home/index.html'
              queryset = About.objects.all()

def get_context_data(self, **kwargs):
    context = super(MyView, self).get_context_data(**kwargs)
    context['Experience'] = Experience.objects.all()
    context['Education'] = Education.objects.all()
    context['Award'] = Award.objects.all()
    context['Membership'] = Membership.objects.all()
    context['About'] = self.queryset
    return context

如果你正在傳遞查詢集,那么請嘗試循環它們並訪問每個圖像

{% for data in About %}
 <img src="{{data.image.url}}" alt="profile photo">
{% endfor %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM