如何在Django中获取图像的正确URL

时间:2016-12-15 16:05:47

标签: python django

您好我是Django的新手,我正在尝试构建一个简单的电子商务应用程序。在这个应用程序中,我希望用户上传他们想要出售的项目的照片。我想显示主页中的所有项目,当您点击项目名称时,它会重定向到项目详细信息页面。用户可以添加具有以下字段标题,项目图像和描述的新项目。我想在标题附近的主页和项目详细信息页面中显示原始图像的上传图像的缩略图,但是当我尝试这样做时,图像没有出现在详细信息页面中。这是我的代码:

models.py

from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from PIL import Image

class Item(models.Model):
    posted_user = models.ForeignKey('auth.User')
    item_name = models.CharField(max_length=200)
    item_image = models.ImageField(upload_to='img')
    item_discription = models.TextField()
    posted_date = models.DateTimeField(
        default=timezone.now)

forms.py

from django import forms
from .models import Item
import re
from django.contrib.auth.models import User

class SellItemAddForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ('item_name', 'item_discription', 'item_image')

urls.py

from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
url(r'^$', views.item_list, name='item_list'),
url(r'^item/(?P<pk>\d+)/$', views.item_detail, name='item_detail'),
url(r'^item/new/$',views.item_new, name='item_new'),
url(r'^item/(?P<pk>\d+)/edit$', views.item_edit, name='item_edit'),
url(r'^item/(?P<pk>\d+)/remove/$', views.item_remove, name='item_remove'),
]
if settings.DEBUG:
    urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

from django.shortcuts import render, get_object_or_404
from .models import Item
from django.utils import timezone
from .forms import SellItemAddForm
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required


def item_list(request):
    items = Item.objects.filter(posted_date__lte=timezone.now())
    return render(request, 'sbApp/item_list.html',{'items': items})

def item_detail(request, pk):
    item = get_object_or_404(Item, pk=pk)
    return render(request, 'sbApp/item_detail.html', {'item': item})

def item_remove(request, pk):
    item = get_object_or_404(Item, pk=pk)
    item.delete()
    return redirect('item_list')

@login_required
def item_new(request):
    if request.method == "POST":
        form = SellItemAddForm(request.POST)
        if form.is_valid():
            item = form.save(commit=False)
            item.posted_user = request.user
            item.posted_date = timezone.now()
            item.save()
            return redirect('item_detail', pk=item.pk)
    else:
        form = SellItemAddForm()
    return render(request, 'sbApp/new_item.html', {'form': form})

@login_required
def item_edit(request, pk):
    item = get_object_or_404(Item, pk=pk)
    if request.method == "POST":
        form = SellItemAddForm(request.POST, instance=item)
        if form.is_valid():
            item = form.save(commit=False)
            item.posted_user = request.user
            item.posted_date= timezone.now()
            item.save()
            return redirect('item_detail', pk=item.pk)
    else:
        form = SellItemAddForm(instance=item)
    return render(request, 'sbApp/item_edit.html', {'form': form})

item_detail.html

{% extends 'sbApp/base.html' %}

{% block content %}
<div class="item">


    {% if user.is_authenticated %}
    <a class="btn btn-default" href="{% url 'item_remove' pk=item.pk %}"><span class="glyphicon glyphicon-remove"></span></a>
    <a class="btn btn-default" href="{% url 'item_edit' pk=item.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
    {% endif %}

    <h1>{{ item.item_name }}</h1>
    {% if item.posted_date %}
        <div class="date">
            <p>posted on {{ item.posted_date }}</p>
        </div>
    {% endif %}
    <div class="user_name">
      <p>by {{item.posted_user}}</p>
    </div>
    <img src="{{ MEDIA_URL }}{{ item.item_image.url }}" alt="img">
    <p>{{ item.item_discription|linebreaksbr }}</p>

</div>
{% endblock %}

item_list.html

{% extends 'sbApp/base.html' %}

{% block content %}
{% for item in items %}
 <div class="item">

   <h1><a href="{% url 'item_detail' pk=item.pk%}">{{ item.item_name }}      </a></h1>
  <div class="date">
    <p>posted on: {{ item.posted_date }}</p>
  </div>
  <p>{{ item.discription }}</p>
 <img src="{{ MEDIA_URL }}{{ item.item_image.url }}" alt="img">
</div>
 {% endfor %}
 {% endblock %}

2 个答案:

答案 0 :(得分:1)

在浏览器中,查看img标记所在模板的源代码,并告诉我们src属性的值是多少?我唯一的猜测是你在模板/的某个地方遗漏了{{ MEDIA_URL }}{{ item.item_image.url }}。假设图像存在并且在某处定义了MEDIA_URL常量。

编辑:

<img src="/{{ MEDIA_URL }}{{ item.item_image.url }}" alt="img">
          ^

听起来您已经形成了一个相对网址,因此如上所示,通过添加/可以使其成为绝对网址。

答案 1 :(得分:1)

{{ MEDIA_URL }}您可以在结合{{ item.item_image.url }}

之前在模板上查看输出结果