图片没有出现在django上

时间:2018-05-10 05:55:39

标签: python django django-models django-templates django-views

我正在尝试克隆www.producthunt.com,当我正在研究它时,我制作了一个模型,人们可以上传产品和标题,身体等的图片。当我制作models.py时, views.py和detail.html [发布后用户被重定向到自己帖子的页面]我发现图片无法显示它有图像符号就是这样! 所以,我的views.py看起来像:

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

def home(request):
    products = Product.objects
    return render(request, 'products/home.html',{'products':products})

@login_required(login_url="/accounts/signup")
def create(request):
    if request.method == 'POST':
        if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']:
            product = Product()
            product.title = request.POST['title']
            product.body = request.POST['body']
            if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
                product.url = request.POST['url']
            else:
                product.url = 'http://' + request.POST['url']
            product.icon = request.FILES['icon']
            product.image = request.FILES['image']
            product.pub_date = timezone.datetime.now()
            product.hunter = request.user
            product.save()
            return redirect('/products/' + str(product.id))
        else:
            return render(request, 'products/create.html',{'error':'All fields are required.'})
    else:
        return render(request, 'products/create.html')

def detail(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    return render(request, 'products/detail.html',{'product':product})

而detail.html看起来像是:

{% extends 'base.html' %}
{% block content %}

<div class="row">
  <div class="col-2">
    <img src="{{ product.icon.url }}" class="img-fluid" />
  </div>
  <div class="col-10">
    <a href="{{ product.url }}"><h1>{{ product.title }}</h1></a>
  </div>
</div>
{% endblock %}

该产品的型号如下:

from django.db import models
from django.contrib.auth.models import User

class Product(models.Model):
    title = models.CharField(max_length=200)
    url = models.TextField()
    pub_date = models.DateTimeField()
    votes_total = models.IntegerField(default=1)
    image = models.ImageField(upload_to='images')
    icon = models.ImageField(upload_to='images')
    body = models.TextField()
    hunter = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def summary(self):
        return self.body[:100]

    def pub_date_pretty(self):
        return self.pub_date.strftime('%b %d %Y')

我有两个urls.py主urls.py看起来像:

from django.contrib import admin
from django.urls import path, include
from products import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name="home"),
    path('accounts/', include('accounts.urls')),
    path('products/', include('products.urls')),
]

/ products / urls.py看起来像:

from django.urls import path, include
from .import views

urlpatterns = [
    path('create', views.create, name='create'),
    path('<int:product_id>/', views.detail, name='detail'),
]

1 个答案:

答案 0 :(得分:1)

product.icon.url return&#39; /media/images/myimage.png'

在项目url.py

中使用此代码
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

图片网址应该是这样的

&#39; http://127.0.0.1:8000/media/images/myimage.png&#39;

在setting.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')


STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

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