我更新时,在heroku上找不到像图像这样的静态文件

时间:2017-05-22 16:15:08

标签: python django angular heroku

目前我正在研究django和angular 2.我正在表演的是。我正在django目录中的文件夹中上传图像并将该路径保存在数据库中。一切正常,它显示了该链接的图像。但每当我更新django项目时,旧的上传文件/图像都不存在更多。

任何人都可以告诉我为什么文件夹中的旧图片不再存在。我该怎么做才能永久存储在服务器上。 任何人都可以建议我。

这是我的 settings.py

    """
Django settings for SNR project.

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

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

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

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#u#9-1dttxl=y2-lfdxsh3udk+k51lyf9z5500@mva4w*(8sus'

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


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'corsheaders',
    'django.contrib.sessions',
    'django.contrib.messages',

    'rest_framework',
    'mobile.apps.MobileConfig',
    'laptop.apps.LaptopConfig',
    'django.contrib.staticfiles',

]

MIDDLEWARE_CLASSES = [
    'corsheaders.middleware.CorsMiddleware',

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

CORS_ORIGIN_ALLOW_ALL=True

CORS_ALLOW_METHODS = (
    'GET',
    'OPTIONS',
)

CORS_ALLOW_HEADERS = (

    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'Content-Type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)
CORS_PREFLIGHT_MAX_AGE=86400

ROOT_URLCONF = 'SNR.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'SNR.wsgi.application'

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

DATABASES = {
    #'default': {
    #    'ENGINE': 'django.db.backends.sqlite3',
    #    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'SNR',
        'USER': 'postgres',
        'PASSWORD': '1234',
        'PASSWORD': '1234',
        'HOST': '',
        'PORT': '5432',

    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = '/static/'

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

import dj_database_url
DATABASES['default'] =  dj_database_url.config()


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

和我的 Model.py

    from __future__ import unicode_literals
from time import time

from django.db import models

def get_name(instance,filename):
    return "uploaded_files/%s_%s"%(str(time()).replace('.','_'),filename)

# Create your models here.
class Laptop(models.Model):
    company_SNR = models.CharField(max_length=100)
    series_SNR = models.CharField(max_length=100)
    model_SNR = models.CharField(max_length=100)
    link_SNR = models.CharField(max_length=1000,default='shopnroar.com')

    Available_SNR=models.CharField(max_length=50,default="SHOPNROAR")
    CompleteName_SNR=models.CharField(max_length=500,default="SHOPNROAR")


    condition_SNR = models.CharField(max_length=50,default='New')
    gen_SNR = models.CharField(max_length=50,default='')

    processorMFG_SNR = models.CharField(max_length=50,default='')
    processorTech_SNR = models.CharField(max_length=50,default='')
    processorSpeed_SNR = models.CharField(max_length=50,default='')
    processorCores_SNR = models.CharField(max_length=50,default='')
    cacheMem_SNR = models.CharField(max_length=50,default='')

    ram_SNR = models.CharField(max_length=50,default='')
    rom_SNR = models.CharField(max_length=50,default='')

    gcard_SNR = models.CharField(max_length=50,default='')
    screensize_SNR = models.CharField(max_length=50,default='')

    sound_SNR = models.CharField(max_length=50,default='')
    battery_SNR = models.CharField(max_length=50,default='')
    hdmi_SNR = models.BooleanField(default=False)
    vga_SNR = models.BooleanField(default=False)
    usbports_SNR = models.CharField(max_length=50,default='')

    price_SNR = models.DecimalField(max_digits=8,decimal_places=2,default=0.00)
    date_SNR = models.DateTimeField(auto_now_add=True, blank=True)

    Image_SNR=models.CharField(max_length=1000000, blank=True)
    ImageThumbnail_SNR=models.FileField(upload_to=get_name, blank=True)
    SNR_Thumbnail=models.FileField( blank=True)



    def __str__(self):
        return  self.company_SNR+' , '+self.series_SNR+' , '+self.model_SNR+' , '+self.link_SNR+' , '+self.condition_SNR+' , '+self.gen_SNR+' , '+self.processorMFG_SNR+' , '+self.processorTech_SNR+' , '+self.processorSpeed_SNR+' , '+self.processorCores_SNR+' , '+self.cacheMem_SNR+' , '+self.ram_SNR+' , '+self.rom_SNR+' , '+self.gcard_SNR+' , '+self.screensize_SNR+' , '+self.sound_SNR+' , '+self.battery_SNR+' , '+str(self.hdmi_SNR)+' , '+str(self.vga_SNR)+' , '+self.usbports_SNR+' , '+str(self.ImageThumbnail_SNR)


    class Meta:
        unique_together = ('company_SNR','series_SNR','model_SNR','link_SNR')

serilzer.py

    from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from .models import Laptop
from drf_extra_fields.fields import Base64ImageField

class Laptop_Serializer(serializers.ModelSerializer):
    ImageThumbnail_SNR = Base64ImageField(required=False,use_url=True)


    class Meta:

        model = Laptop
        fields = ('company_SNR','series_SNR','model_SNR','link_SNR','Available_SNR','CompleteName_SNR','condition_SNR','gen_SNR','processorMFG_SNR','processorTech_SNR','processorSpeed_SNR','processorCores_SNR','cacheMem_SNR','ram_SNR','rom_SNR','gcard_SNR','screensize_SNR','sound_SNR','battery_SNR','hdmi_SNR','vga_SNR','usbports_SNR','ImageThumbnail_SNR')

在这种情况下的任何帮助都会受到高度关注。

1 个答案:

答案 0 :(得分:0)

看起来您正在将图片上传到Heroku应用的文件空间中,您应该这样做。当您的Heroku实例重新启动时(每次重新部署您的应用程序)时,它会将整个文件系统吹走,并从头开始重建您的应用程序。您需要将图像保存在其他地方,例如亚马逊的S3。