[关闭]
@breky 2023-03-08T02:24:59.000000Z 字数 1655 阅读 104

Django 笔记

Django


virtualenvwrapper

安装

  1. pip install virtualenvwrapper

查找 virtualenvwrapper.sh 路径

  1. which virtualenvwrappers.sh # /usr/local/bin/virtualenvwrapper.sh

添加到 .bashrc/.zshrc 中

  1. source /usr/local/bin/virtualenvwrapper.sh

source .bashrc

  1. source /home/username/.bashrc

如果没有 .bashrc/ .zshrc, 则 cd 到 ~ 目录下,新建

  1. cd ~
  2. touch .bashrc

添加 virtualenvwrapper.sh 路径

然后把 .bashrc 添加到 /etc/profile 文件中

  1. sudo vim /etc/profile

在文末添加以下内容:

  1. if [ -e /home/username/.bashrc ]; then
  2. source /home/username/.bashrc
  3. fi
  4. # save and exit

之后, source /etc/profile


使用

新建虚拟环境

  1. mkvirtualenv [--pthon=python3.8] venv
  2. # --python=python3.8 可选,用来指定 python 版本,只安装了一个 python 版本可以省略

激活 venv 虚拟环境

  1. workon venv

命令行显示:

  1. (vnev)....$

退出 venv 虚拟环境

  1. deactivate

删除 venv 虚拟环境

  1. rmvirtualenv venv

安装 Django

django 1.8 需要 python 3.6 以下的版,使用以上的版本,在新建 Post 时会报错。django 2.0.13 安装 python 3.8 以上的版本,以下的版本没测试。

搭建环境为: django 2.0.13、python 3.8

进入 venv 虚拟环境,再安装 django

  1. (venv).....$ pip install django==2.0.*

开始

启动项目

  1. django-admin startproject mysite

创建 app

  1. python manage.py startapp blog

设计 blog 数据模型
编辑 blog/models.py 文件,添加以下内容

  1. from django.db import models
  2. from django.db.utils import timezone
  3. from django.contrib.auth.models import User
  4. class Post(models.Model):
  5. STATUS_CHOICES = (
  6. ('draft', 'Draft'),
  7. ('published', 'Published'),
  8. )
  9. title = models.CharField(max_length=250)
  10. slug = models.SlugField(max_length=250,
  11. unique_for_date='publish')
  12. author = models.ForeignKey(User,
  13. on_delete=models.CASCADE,
  14. related_name='blog_posts')
  15. body = models.TextField()
  16. publish = models.DateTimeField(default=timezone.now)
  17. created = models.DateTimeField(auto_now_add=True)
  18. updated = models.DateTimeField(auto_now=True)
  19. status = models.CharField(max_length=10,
  20. choices=STATUS_CHOICES,
  21. default='draft')
  22. class Meta:
  23. ordering = ('-publish',)
  24. def __str__(self):
  25. return self.title

迁移数据模型

  1. python manage.py makemigrations blog
  2. python manage.py migrate

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注