构建Django在Heroku上部署的环境以及解决错误
一开始
之前在anaconda虚拟环境下创建了Django的Web应用程序,但在Heroku上无法部署,困扰了我将近半年的时间。我将记录下我遇到的错误和解决方案。如果对遇到相同错误的人有所帮助,我将感到非常幸福。
###错误(1)
requirements.txt太多了
在中国,采取以下解决策:
重新构建虚拟环境(请稍后查看详细方法)。
###错误(2)
pys…
###解决方案
安装postgreSQL
###错误(3)
Python路径未设置
###解决方案
设置Python路径
#今天要做的事
可能还有其他错误,但我只记得上面的三个。
接下来,我会介绍如何在Heroku上构建可以部署的虚拟环境。
部署到Heroku的方法请参考以下文章。
虽然是其他人的文章,但这篇文章详细地写了。
环境
请在使用Heroku进行部署时先安装Git Bash,因为需要使用github。下载链接在这里。
在本文中,几乎所有的命令都使用Git Bash输入。
构建环境
$ mkdir heroku_deploy //ディレクトリを作成
$ cd heroku_deploy
$ python -m venv env //仮想環境を構築
激活或停用虚拟环境
在env文件夹的位置上启用虚拟环境。
$ ls //ディレクトリ内にあるファイルの一覧を表示
如果在Windows上使用Git Bash的情况下
$ source ./env/Scripts/activate //仮想環境の有効化
$ deactivate //仮想環境の無効化
如果运行Windows系统,您要使用命令提示符的话
$ env\Scripts\activate //仮想環境の有効化
$ deactivate //仮想環境の無効化
安装
$ pip install --upgrade pip
$ pip install --upgrade setuptools
$ pip install django
$ pip list
创建一个 Django 项目。
$ django-admin startproject web_test
$ cd web_test
$ python manage.py migrate
$ python manage.py runserver //WEBサーバー起動
使用浏览器访问 http://localhost:8000/hello 。
创建 Django 应用程序
($ cd web_test)
$ python manage.py startapp hello
heroku_deploy
|-----env(仮想環境、触らない)
|-----web_test
|------hello
|------web_test(settings.pyなど)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello', # 追加
]
创建HTML和CSS
heroku_deploy
|-----env(仮想環境、触らない)
|-----web_test
|------hello(htmlとかcssとか)
|-------templates #追加
|--------hello #追加
|-------index.html #追加
|------web_test(設定ファイルなど
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>hello</title>
</head>
<body>
<h1>こんにちは</h1>
<p>サンプルページです。</p>
</body>
</html>
from django.contrib import admin
from django.urls import path
import hello.views as hello
urlpatterns = [
path('admin/',admin.site.urls),
path('hello/',hello.index)
]
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'hello/index.html')
我会启动Web服务器并确认它是否正常运行。
$ python manage.py runserver
在浏览器中访问http://localhost:8000/hello
应用CSS
将静态文件(如图像文件、CSS等)放入“static”文件夹中。
heroku_deploy
|-----env(仮想環境、触らない)
|-----web_test
|------hello(htmlとかcssとか)
|-------static #追加
|--------hello #追加
|-------style.css #追加
|------web_test(設定ファイルなど
body{
color:gray;
font-size:16pt;
}
h1{
color:blue;
opacity:0.2;
font-size:60pt;
margin-top:-20pt;
margin-bottom:0px;
}
p{
margin:10px;
}
a{
color:blue;
text-decoration:none;
}
修改index.html。
{% load static %}
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="{% static 'hello/css/style.css' %}" />
<title>hello</title>
</head>
<body>
<h1>こんにちは</h1>
<p>CSS反映した</p>
</body>
</html>
我会启动WEB服务器并确认它是否正常运行。
$ python manage.py runserver
通过浏览器访问 http://localhost:8000/hello
在Heroku上部署
另一位的话,请参考这篇文章,内容详细说明了。
不是扔下的意思