我正在尝试从我的媒体文件夹中加载图片但无法正常工作,我输出的是{{ image.image.url }}
显示/media/products/yo.jpg
这里是我的结构
这是我想要加载图像实例中的图像的块。 我认为我的代码不好也许你可以给出一些建议。
{% block content %}
<!-- all products-->
<section >
{% for product in products %}
{% for image in images %}
<div class="product">
<img src="{% static 'img/vaca.jpg' %}" class="imgpro">
<div class="info">
<p>
<h3> Product: </h3> {% if image.product.pk == product.pk %} <img src='{{ image.image.url }}' class="imgpro"> {% endif %}
<h3> Offer: </h3> <a href="{% url 'ganagroapp:product_detail' pk=product.pk %}">{{ product.product }}</a>
<h3> Description: </h3> {{ product.description }}
</p>
</div>
</div>
{% endfor %}
{% endfor %}
</section>
{% endblock content %}
这是我的网址:
from django.conf.urls import include, url
from . import views
from django.contrib.auth.views import login
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.views import logout
app_name = 'ganagroapp'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail, name='product_detail'),
url(r'^category/(?P<pk>[0-9]+)/$', views.product_category, name='product_category'),
url(r'^product/new/$', views.new_product, name='new_product'),
url(r'^login/$',login,{'template_name':'login.html'}, name='login'),
url(r'^logout/$',logout,{'template_name':'index.html'},name='logout'),
]
this is my view
def index(request):
images = Image.objects.select_related()
category = Category.objects.select_related()
products = Product.objects.select_related()
return render(request,'ganagroapp/index.html', {'category' : category, 'products' : products, 'images': images} )
这是设置文件
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'ganagroapp', 'media')
LOGIN_REDIRECT_URL = reverse_lazy('ganagroapp:index')
答案 0 :(得分:2)
我认为问题是因为您没有在urls.py中添加最后一行:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)