@breky
2023-03-08T02:24:59.000000Z
字数 1655
阅读 104
Django
pip install virtualenvwrapper
查找 virtualenvwrapper.sh 路径
which virtualenvwrappers.sh # /usr/local/bin/virtualenvwrapper.sh
添加到 .bashrc/.zshrc 中
source /usr/local/bin/virtualenvwrapper.sh
source .bashrc
source /home/username/.bashrc
如果没有 .bashrc/ .zshrc, 则 cd 到 ~ 目录下,新建
cd ~touch .bashrc
添加 virtualenvwrapper.sh 路径
然后把 .bashrc 添加到 /etc/profile 文件中
sudo vim /etc/profile
在文末添加以下内容:
if [ -e /home/username/.bashrc ]; thensource /home/username/.bashrcfi# save and exit
之后, source /etc/profile
新建虚拟环境
mkvirtualenv [--pthon=python3.8] venv# --python=python3.8 可选,用来指定 python 版本,只安装了一个 python 版本可以省略
激活 venv 虚拟环境
workon venv
命令行显示:
(vnev)....$
退出 venv 虚拟环境
deactivate
删除 venv 虚拟环境
rmvirtualenv venv
django 1.8 需要 python 3.6 以下的版,使用以上的版本,在新建 Post 时会报错。django 2.0.13 安装 python 3.8 以上的版本,以下的版本没测试。
搭建环境为: django 2.0.13、python 3.8
进入 venv 虚拟环境,再安装 django
(venv).....$ pip install django==2.0.*
启动项目
django-admin startproject mysite
创建 app
python manage.py startapp blog
设计 blog 数据模型
编辑 blog/models.py 文件,添加以下内容
from django.db import modelsfrom django.db.utils import timezonefrom django.contrib.auth.models import Userclass Post(models.Model):STATUS_CHOICES = (('draft', 'Draft'),('published', 'Published'),)title = models.CharField(max_length=250)slug = models.SlugField(max_length=250,unique_for_date='publish')author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts')body = models.TextField()publish = models.DateTimeField(default=timezone.now)created = models.DateTimeField(auto_now_add=True)updated = models.DateTimeField(auto_now=True)status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')class Meta:ordering = ('-publish',)def __str__(self):return self.title
迁移数据模型
python manage.py makemigrations blogpython manage.py migrate