Task01
一.创建虚拟环境
-
python -m venv django_learn
(django_learn那里是自己定的环境名字) -
之前一直用conda管理虚拟环境,没咋用过virtualenv,然后我的powershell之前也设置了默认启动了base环境,然后输入activate命令之后好像没啥反应,试了下pip list,输出一堆东西,看来是没成功切换环境,去问了下Claude,得先conda deactivate,然后再activate就ok了,前面就会显示创建的虚拟环境,出现了
django_learn
-
powershell和cmd的不同
- powershell下面是输入
activate
命令 - cmd里面要输入
activate.bat
命令
- powershell下面是输入
-
习惯用powershell,之后还是用powershell,powershell里面
-
然后安装依赖
pip install -r requirements.txt
二.创建 Django项目和 APP
我创建的Django项目叫firstProj,APP叫FirstApp
-
首先创建Django项目
pythondjango-admin startproject firstProj
-
产生的结构是
python- firstProj - firstProj(下面有文件) - manage.py
-
然后创建APP
在项目下面新建一个apps文件夹,然后cd进去,输入命令
pythondjango-admin startapp firstApp
-
去apps.py改个名
-
接着去settings.py中注册
增加几个插件
python'rest_framework', 'django_filters', 'drf_spectacular',
三.启动!
运行项目先执行数据库迁移相关操作,再启动 django 项目
python
# 执行数据库迁移相关操作
python manage.py makemigrations
python manage.py migrate
# 启动django
python manage.py runserver
-
models.py中可以构建数据表
python# from django.db import models from django.db.models import * # Create your models here. class Test(Model): name = CharField(max_length=100)
-
成功启动!
四.创建数据表
文档里给的代码不知道为啥报这个错
python
SystemCheckError: System check identified some issues:
ERRORS:
firstApp.Goods.category: (fields.E300) Field defines a relation with model 'goods.GoodsCategory', which is either not installed, or is abstract.
firstApp.Goods.category: (fields.E307) The field firstApp.Goods.category was declared with a lazy reference to 'goods.goodscategory', but app 'goods' isn't installed.
下面代码经过claude修改,python [manage.py](http://manage.py/) makemigrations
和python manage.py migrate成功了
python
from django.db import models
class GoodsCategory(models.Model):
name = models.CharField(max_length=64, verbose_name='名称')
remark = models.CharField(max_length=256, null=True, blank=True, verbose_name='备注')
class Goods(models.Model):
number = models.CharField(max_length=32, verbose_name='编号')
name = models.CharField(max_length=64, verbose_name='名称')
barcode = models.CharField(max_length=32, null=True, blank=True, verbose_name='条码')
# 修复代码:
category = models.ForeignKey(GoodsCategory, null=True, on_delete=models.SET_NULL, related_name='goods_set', verbose_name='产品分类')
spec = models.CharField(max_length=64, null=True, blank=True, verbose_name='规格')
shelf_life_days = models.IntegerField(null=True, verbose_name='保质期天数')
purchase_price = models.FloatField(default=0, verbose_name='采购价')
retail_price = models.FloatField(default=0, verbose_name='零售价')
remark = models.CharField(max_length=256, null=True, blank=True, verbose_name='备注')