KiranChavan
KiranChavan

Reputation: 13

Picture not showing up on django

I am trying to make clone of www.producthunt.com and while I was working on it I made model by which people can upload the picture of the product and title, body, etc. While I made the models.py, views.py, and the detail.html[Page where the user gets redirected to his own post after posting] I found that the picture wasn't able to showup it had an image symbol and that's it! So, my views.py looks like:

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})

And the detail.html looks like:

{% 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 %}

The product's model looks like:

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')

I have two urls.py the main urls.py looks like:

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')),
]

And the /products/ urls.py looks like:

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

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

Upvotes: 1

Views: 2312

Answers (1)

Ravi Bhushan
Ravi Bhushan

Reputation: 952

product.icon.url return '/media/images/myimage.png'

Use this code in project 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)

image URL should be like this

'http://127.0.0.1:8000/media/images/myimage.png'

in 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/'

Upvotes: 2

Related Questions