Image is not showing in admin pannel

65 views Asked by At

The image: My index.html:

<div class="product-main">

            <h2 class="title">New Products</h2>

            <div class="product-grid">


              {%  for i in products  %}

                <div class="showcase">

                  <div class="showcase-banner">
                    <a href="#">
                      <img src="{{  i.image.url  }}" alt="" />
                      <img src="{{  i.image.url  }}" alt="" />
                    </a>

                    <p class="showcase-badge">15%</p>

                    
                  </div>
                </div>
              {%  endfor  %}

Admin.py:

from django.contrib import admin
from core.models import *

# Register your models here.


class ProductImagesAdmin(admin.TabularInline):
    model= ProductImages

class ProductAdmin(admin.ModelAdmin):
    inlines=[ProductImagesAdmin]
    list_display=['user','title','product_image','price','featured','product_status']

class CategoryAdmin(admin.ModelAdmin):
    list_display=['title','catagory_image']

class VendorAdmin(admin.ModelAdmin):
    list_display=['title','Vendor_image']

class CartOrderAdmin(admin.ModelAdmin):
    list_display=['user','price','paid_status','order_date','product_status']

class CartOrderItemsAdmin(admin.ModelAdmin):
    list_display=['order','invoice_num','product_status','item','image','qty','price','total']

class ProductReviewAdmin(admin.ModelAdmin):
    list_display=['user','product','review','rating','date']

class wishlistAdmin(admin.ModelAdmin):
    list_display=['user','product','date']

class AddressAdmin(admin.ModelAdmin):
    list_display=['user','address','status']

admin.site.register(Product,ProductAdmin)
admin.site.register(Category,CategoryAdmin)
admin.site.register(Vendor,VendorAdmin)
admin.site.register(CartOrder,CartOrderAdmin)
admin.site.register(CartOrderItems,CartOrderItemsAdmin)
admin.site.register(ProductReview,ProductReviewAdmin)
admin.site.register(wishlist,wishlistAdmin)
admin.site.register(Address,AddressAdmin)



Models.py:

# from email.policy import default
# from pyexpat import model
from django.db import models
# from unicodedata import decimal
from shortuuid.django_fields import ShortUUIDField
from django.utils.html import mark_safe
from userauths.models import CustomUser



STATUS_CHOICE=(
    ("process","Processing"),
    ("shipped","Shipped"),
    ("delevered","Delevered"),
)



STATUS=(
    ("draft","Draft"),
    ("disable","Disable"),
    ("rejected","Rejected"),
    ("In_review","In Review"),
    ("published","Published"),
)


RATING=(
    (1,"⭐☆☆☆☆"),
    (2,"⭐⭐☆☆☆"),
    (3,"⭐⭐⭐☆☆"),
    (4,"⭐⭐⭐⭐☆"),
    (5,"⭐⭐⭐⭐⭐"),
)
# Create your models here.

def user_directory_path(instance,filename):
    return 'user_{0}/{1}'.format(instance.user.id, filename)


class Category(models.Model):
    cid=ShortUUIDField(length=10,max_length=100,prefix="cat",alphabet="abcdef")
    title=models.CharField(max_length=100,default="Food")
    image=models.ImageField(upload_to="category",default="category.jpg")

    class Meta:
        verbose_name_plural="Categories"

    def catagory_image(self):
        return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url))

    def __str__(self):
        return self.title


class Tags(models.Model):
    pass

class Vendor(models.Model):
    vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef")


    title=models.CharField(max_length=100,default="Nest")
    image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg")
    description=models.TextField(null=True, blank=True,default="Normal Vendorco")


    address=models.CharField(max_length=100, default="6,Dum Dum Road")
    contact=models.CharField(max_length=100, default="+91")
    chat_resp_time=models.CharField(max_length=100,default="100")
    shipping_on_time=models.CharField(max_length=100,default="100")
    authenticate_rating=models.CharField(max_length=100,default="100")
    days_return=models.CharField(max_length=100,default="100")
    warranty_period=models.CharField(max_length=100,default="100")


    user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)


    class Meta:
        verbose_name_plural="Vendors"

    def Vendor_image(self):
        return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url))

    def __str__(self):
        return self.title

class Product(models.Model):
    pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef")


    user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
    cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True)


    title=models.CharField(max_length=100,default="Apple")
    image=models.ImageField(upload_to=user_directory_path,default="product.jpg")
    description=models.TextField(null=True, blank=True,default="This is a product")

    price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99)
    old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99)

    specifications=models.TextField(null=True, blank=True)
    # tags=models.ForeignKey(Tags, on_delete=models.SET_NULL ,null=True)

    product_status=models.CharField(choices=STATUS, max_length=10,default="In_review")


    status=models.BooleanField(default=True)
    in_stock=models.BooleanField(default=True)
    featured=models.BooleanField(default=False)
    digital=models.BooleanField(default=False)

    sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef")

    date=models.DateTimeField(auto_now_add=True)
    updated=models.DateTimeField(null=True,blank=True)

    class Meta:
        verbose_name_plural="Products"

    def product_image(self):
        return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url))

    def __str__(self):
        return self.title
    def get_percentage(self):
        new_price=(self.price/self.old_price) * 100
        return new_price

class ProductImages(models.Model):
    images=models.ImageField(upload_to="product-image",default="product.jpg")
    product=models.ForeignKey(Product, on_delete=models.SET_NULL ,null=True)
    date=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural="Product Images"



######################################################Care,Order,CartItemsand Address###########################

class CartOrder(models.Model):
    user=models.ForeignKey(CustomUser,on_delete=models.CASCADE)
    price= models.DecimalField(max_digits=10, decimal_places=2,default="1.99")
    paid_status=models.BooleanField(default=False)
    order_date=models.DateTimeField(auto_now_add=True)
    product_status=models.CharField(choices=STATUS_CHOICE, max_length=30,default="prodcessing")

    class Meta:
        verbose_name_plural="Cart Order"

class CartOrderItems(models.Model):
    order=models.ForeignKey(CartOrder,on_delete=models.CASCADE)
    invoice_num = models.BigIntegerField(blank=True,null=True)
    product_status=models.CharField(max_length=200)
    item=models.CharField(max_length=100)
    image=models.CharField(max_length=100)
    qty=models.BigIntegerField(default=0)
    price= models.DecimalField(max_digits=12, decimal_places=2,default="15")
    total= models.DecimalField(max_digits=12, decimal_places=2,default="20")

    class Meta:
        verbose_name_plural="Cart Order Items"

    def oder_img(self):
        return mark_safe('<img src="/media/%s" width="50" height="50"/>'%(self.image))


###########################Product Revew, wishlist, Address############################################

class ProductReview(models.Model):
    user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
    product=models.ForeignKey(Product, on_delete=models.SET_NULL ,null=True)
    review=models.TextField()
    rating = models.BigIntegerField(choices=RATING, default=3)

    date=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural="Product Reviews"

    def __str__(self):
        return self.product.title

    def get_rating(self):
        return self.rating



class wishlist(models.Model):
    user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
    product=models.ForeignKey(Product, on_delete=models.SET_NULL ,null=True)
    date=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural="wishlists"

    def __str__(self):
        return self.product.title



class Address(models.Model):
    user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
    address=models.CharField(max_length=100, null=True)
    status=models.BooleanField(default=False)

    class Meta:
        verbose_name_plural="Address"












In the screenshot why images are not displaying. I think my code is right. What is going on then? and only the problem is with the image other things works perfectly. Even in index.html produts are showing but images are not able to display. I also ran all the migrations commands.

settings.py:

"""
Django settings for ecomprj project.

Generated by 'django-admin startproject' using Django 5.0.1.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-^mlg-*n8+um7^s$ivuodjy$sma!&ilikxhs^!t69k#&kuj-$gd'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'jazzmin',
    'core.apps.CoreConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Custom Apps
    # 'core',
    'userauths'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ecomprj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ecomprj.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR , 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'

STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles')

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

MEDIA_URL='/media/'

MEDIA_ROOT=os.path.join(BASE_DIR,"media")

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


JAZZMIN_SETTINGS={
    'site_header':"Sagarmoy Shop",
    'site_brand':"Sagarmoy Shop",
    'site_logo':"assets/images/logo/logo1.jpg",
    'site_copyright':"Sagarmoy Shop.com"
}

AUTH_USER_MODEL = 'userauths.CustomUser'

urls.py

"""
URL configuration for ecomprj project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include

from django.conf import settings
from django.conf.urls.static import static
from  userauths import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path("",include("core.urls")),
    path("user/",include("userauths.urls")),
    path('register/', views.register, name='register'),
    path('userauths/', include('django.contrib.auth.urls')),
    path('login/', views.LoginPage, name='login'),
    path('userauths/', include('userauths.urls')),
    path('person/', views.person, name='person'),

]


urlpatterns +=static(settings.STATIC_URL)
1

There are 1 answers

0
Sagarmoy Sadhukhan On BEST ANSWER

Change in settigs.py from STATIC_URL = 'static/' to

STATIC_URL = '/static/'

this