P4YK
@P4YK

Не работает Static и Media?

Не работает изображение на главной странице и не работают изображения в каталоге товаров.
60a379dfcc06e503929217.png
60a379e805eb5402464105.png

urls.py :
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

from rest_framework_jwt.views import (obtain_jwt_token,
                                      verify_jwt_token,
                                      refresh_jwt_token)

from catalog.api.views import (
    APIRoot,
    CategoryListAPIView,
    CategoryDetailAPIView,
    ProductListAPIView,
    ProductDetailAPIView,
    ProductCreateAPIView,
    ProductDetailUpdateAPIView,
)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('account/', include('account.urls')),
    path('cart/', include('cart.urls', namespace='cart')),
    path('orders/', include('orders.urls', namespace='orders')),
    path('payment/', include('payment.urls', namespace='payment')),
    path('', include('catalog.urls', namespace='catalog')),
    path('social-auth/', include('social_django.urls', namespace='social')),
]

urlpatterns += [
    path('api/', APIRoot.as_view(), name='api_root'),

    path('api/jwt/', obtain_jwt_token, name='jwt'),
    path('api/refresh/', refresh_jwt_token, name='refresh'),

    path('api/products/', ProductListAPIView.as_view(), name='products_api'),
    path('api/products/<int:pk>/', ProductDetailAPIView.as_view(),
         name='products_detail_api'),
    path('api/products/new/', ProductCreateAPIView.as_view(), name='products_create_api'),
    path('api/products/<int:pk>/update/', ProductDetailUpdateAPIView.as_view(),
         name='products_detail_update_api'),

    path('api/categories/', CategoryListAPIView.as_view(), name='category_api'),
    path('api/categories/<int:pk>/', CategoryDetailAPIView.as_view(),
         name='category_detail_api'),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)


settings.py :
import os
import datetime
from decouple import config
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY', 'dummy_secret_key')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', 'True', cast=bool)

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'account.apps.AccountConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    "django.contrib.sites",
    'django.contrib.staticfiles',
    'catalog.apps.CatalogConfig',
    'cart.apps.CartConfig',
    'orders.apps.OrdersConfig',
    'payment.apps.PaymentConfig',
    'newsletter.apps.NewsletterConfig',
    'social_django',
    'django_extensions',
    'django_countries',
    'rest_framework',
    'corsheaders',
    'storages',
    'django_filters',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    # 'whitenoise.middleware.WhiteNoiseMiddleware',
    'catalog.middleware.MoreWhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'catalog.middleware.SqueakyCleanMiddleware',
]

MORE_WHITENOISE = [
    {"directory": os.path.join(BASE_DIR, "blog_out"), "prefix": "blog/"},
]

WHITENOISE_INDEX_FILE = True

ROOT_URLCONF = 'marketplace.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',
                'cart.context_processors.cart',
            ],
        },
    },
]

WSGI_APPLICATION = 'marketplace.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/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/3.1/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/3.1/topics/i18n/

LANGUAGE_CODE = 'fr-fr'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

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

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

LOGIN_REDIRECT_URL = 'profile'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'social_core.backends.google.GoogleOAuth2',
]

SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 1209600  # 2 weeks
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_SECURE = False

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config(
    'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY', 'dummy')
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config(
    'SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET', 'dummy')

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

CART_SESSION_ID = 'cart'



# Email
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"

# django.contrib.sites
SITE_ID = 1

# Task async
CELERY_BROKER_URL = config('REDIS_URL', 'redis://localhost:6379/0', cast=str)
CELERY_RESULT_BACKEND = config(
    'REDIS_URL', 'redis://localhost:6379/0', cast=str)

# Cors
CORS_ORIGIN_WHITELIST = (
    'https://marketplace-fr.herokuapp.com',
    'http://localhost:8100',
    'https://marketplace-fr.netlify.app',
)

CORS_URLS_REGEX = r'^/api/.*$'

# Rest framework
REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.NamespaceVersioning',
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
    'DEFAULT_PAGINATION_CLASS': 'catalog.api.pagination.CatalogPagination',
    'SEARCH_PARAM': 'q',
    'ORDERING_PARAM': 'ordering',
}

# JWT
JWT_AUTH = {
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'marketplace.utils.jwt_response_payload_handler',
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=30000),
    'JWT_ALLOW_REFRESH': True,
}


На телефоне все отображается, на компьютере куки все чистил.60a3849c532f8369391830.jpeg
  • Вопрос задан
  • 40 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы