时间:2023-05-31 14:12:02 | 来源:网站运营
时间:2023-05-31 14:12:02 来源:网站运营
第26期-Django开发-Task2快速搭建网站:python3 manage.py startapp APPNAME
settings.py修改INSTALLED_APPS加入APPNAMEpython3 manage.py createsuperuser
但是在创建前应该先同步数据库python3 manage.py migrate
根据提示进行输入。成功后可以看到如下画面:from django.db import models# Create your models here.class Blog(models.Model): title = models.CharField(max_length=50, verbose_name="标题") content = models.TextField(verbose_name="文章内容", default="") count = models.IntegerField(verbose_name="阅读次数", default=0) creat_time = models.DateTimeField(auto_now=True, verbose_name="创建时间") class Meta: verbose_name = '博客管理' verbose_name_plural = verbose_name def __str__(self): return self.title
from django.contrib import adminfrom .models import Blog# Register your models here.@admin.register(Blog)class BlogAdmin(admin.ModelAdmin): list_display=("title", "creat_time", "count")
同步到数据库python3 manage.py makemigrationspython3 manage.py migrate
注意一行一行的输入verbose_name,显示的名字
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', ], }, },]
在添加 os.path.join(BASE_DIR, "templates")前记得先经 os 库导入进来views.py
from django.shortcuts import render# Create your views here.def index(request): return render(request, "index.html")
将我们定义的方法引入进来,然后定义好访问什么路径来执行这个方法在 templates 文件夹下创建一个 html 文件
def read_blog(request,id): print(f"{id}:我是通过前端点击链接来的") blog = Blog.objects.get(id=id) return render(request, "content.html", {"blog":blog})
urls.pyfrom blog.views import read_blogurlpatterns = [ path('admin/', admin.site.urls), path("", index, name="index"), path("read/<int:id>", read_blog, name="read_blog"),]
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blog', 'USER': 'blog', 'PASSWORD': '你的密码', 'HOST': '虚拟机的IP', 'PORT': '3306', }}
config里面的__init__.pyimport pymysqlpymysql.install_as_MySQLdb()
mysql -u root -p
进入MySQL终端后use mysql;update user set host = '%' where user = 'root'; # 此处的root改为想要远程登录的账号select host, user from user;
参考链接:GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' IDENTIFIED BY 'mypassword' WITH GRANT OPTION;
如果你想允许用户myuser从ip为192.168.1.3的主机连接到mysql服务器,并使用mypassword作为密码GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.3' IDENTIFIED BY 'mypassword' WITH GRANT OPTION;flush privileges; #一定要加上这一句
如果是低版本的MySQL,记得把配置文件my.ini做如下操作#bind-address = 127.0.0.1
这一行注释掉sudo apt install supervisor -y
pip3 install gunicorn
它的配置要比用 uwsgi 方便很多
#!/bin/bash#项目的根目录NAME="MyBlog"DJANGODIR=/DjangoDev/www/MyBlog #Django project directoryUSER=root # the user to run asGROUP=root # the group to run asNUM_WORKERS=1 # how many worker processes should Gunicorn spawnDJANGO_SETTINGS_MODULE=config.settings # which settings file should Django useDJANGO_WSGI_MODULE=config.wsgi # WSGI module nameecho "Starting $NAME as `whoami`"# Activate the virtual environment# 虚拟环境的路径cd $DJANGODIRsource /DjangoDev/env/bin/activateexport DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULEexport PYTHONPATH=$DJANGODIR:$PYTHONPATH# Create the run directory if it doesn't existRUNDIR=$(dirname $SOCKFILE)test -d $RUNDIR || mkdir -p $RUNDIR# Start your Django Unicorn# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)# gunicorn的路径,一般在虚拟环境的bin目录下exec /DjangoDev/env/bin/gunicorn ${DJANGO_WSGI_MODULE}:application /--name $NAME /--workers $NUM_WORKERS /--user=$USER --group=$GROUP /--log-level=debug /--log-file=-
USER=server # the user to run as
GROUP=server # the group to run as
这里的用户名要改为自己的,管理员就是root
chmod +x gunicorn_start.sh
./gunicorn_start.sh
location /static/ { #静态文件目录 alias /DjangoDev/www/MyBlog/static; expires max; access_log off; log_not_found off; }location / {#Django地址 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8000; break; } }
sudo vim /etc/supervisor/conf.d/myblog.conf
并写入如下内容[program:myblog]command = /DjangoDev/www/MyBlog/gunicorn_start.shuser = rootautostart=trueautorestart=trueredirect_stderr = truestdout_logfile = /var/log/myblog.logstderr_logfile = /var/log/myblog.err
user = root最后更新一下我们设置的一系列内容
同样也要修改成为自己的用户名
sudo supervisorctl updatesudo supervisorctl reload
STATIC_ROOT = os.path.join(BASE_DIR, "static")
并在项目目录下新建一个 static 的文件夹python3 manage.py collectstatic
location ~ /.(eot|otf|ttf|woff|woff2|svg)$ { add_header Access-Control-Allow-Origin *; }
关键词: