我正在设置一个Heroku网站,以为学校项目部署Django应用。问题在于在Django中使用whitenoise的静态文件。
快速上下文:我的应用程序包含一个表单,该表单采用4个值,我在脚本内使用它们进行快速数学计算。该脚本的目的是执行计算,使用matplotlib绘制图并将其保存在我的django应用的静态文件夹中,以替换旧的已有的旧文件夹。该静态文件用于在网站上的html页面中显示。在本地每次提交新表单时,它都像魅力一样可更新情节。但是,当我尝试使用Heroku时,会抛出一个
[Errno 2]没有这样的文件或目录:'/Users/jeff/Desktop/trydjango/src/static/yield_curve.png'
我提交表单时。
这是关于静态文件的settings.py
:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
我的目录如下:
src
|-- /TER
|-- -- /settings.py
|-- /graph
|-- /static/...
|-- /staticfiles/...
|-- /manage.py
我希望我的网站每次使用保存在静态文件夹中的新yield_curve.png
提交表单时刷新图像。
如果我不得不猜测,我会说这与以下事实有关:静态文件必须是“静态”的,并且不能随时间变化。
答案 0 :(得分:0)
我相信您无法使用免费/基本的Heroku帐户保存/更新文件。静态文件必须保持静态且不变。几年前,我本人尝试通过学校项目做同样的事情。这是我将值传递到JS图表以动态呈现图形的方式,因此不必使用文件:
views.py
def some_function(request):
# Do your calculations on the data here
data = [1,2,3,4] # Let's say this is the results
# Pass data in your context to the template
context = { "my_data" : data }
my_template.html
<!-- Before including your JS file -->
<script> var my_passed_data = {{ my_data|safe }} </script>
<script "include your JS file (test.js in this example) which uses the my_passed_data to make a figure>
test.js
// Whatever library you use to render a chart will be here, I'm using CanvasJS for this example
var chart = new CanvasJS.Chart("chartContainer", {
** all your options, etc. **
data: [
{
** all the other stuff such as type, name, etc. **
dataPoints: [
{ x: 0, y: my_passed_data[0] }, // here is where you access your passed data by index
{ x: 2, y: my_passed_data[1] },
这是我如何将数据从“视图”传递到“模板”到JS,以使用CanvasJS绘制图表而不需要任何文件的方法。我不确定这是否是最好的方法,但对我有用,希望这对您的学校项目有帮助并祝您好运!
答案 1 :(得分:0)
并将其保存在我的django应用程序的静态文件夹中,如果它已经存在,则替换旧的应用程序
是的,这在Django中是可能的。不,由于其ephemeral filesystem,在Heroku上是不可能的。您可以覆盖文件,但是下次您的dyno重新启动时,该更改将丢失。 happens frequently(每天至少一次)。
Heroku officially recommends在第三方服务(例如Amazon S3)上存储用户上传的内容和静态文件。 Whitenoise disagrees。您可以在Heroku上使用Whitenoise,但不能(持久地)修改静态文件而无需重新部署。
请注意,无论您的测功机使用何种计划,这都是正确的。免费或企业级的dyno文件系统都是短暂的。