创建[app名称]模块
python manage.py startapp [app名称]
添加到项目settings.py的INSTALL_APPS中
# mysite/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'[app名称]',
]
然后把[app名称]下的路由添加到项目的urls.py中取
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('tasks/', include('tasks.urls'))
]
创建[app名称]模型及其关联表单
模型很简单 仅包含name和status两个字段 我们还使用ModelForm类创建了XxxForm 在创建或者更新的时候要用到这个表单
# tasks/models.py
from django.db import models
class Status(models.TextChoices):
UNSTARTED = 'u', "Not started yet"
ONGOING = 'o', "Ongoing"
FINISHED = 'f', "Finished"
class Animals(models.Model):
name = models.CharField(verbose_name="Task name", max_length=65, unique=True)
status = models.CharField(verbose_name="Task status", max_length=1, choices=Status.choices)
def __str__(self):
return self.name
# tasks/forms.py
from .models import Task
from django import forms
class AnimalsForm(forms.ModelForm):
class Meta:
model = Task
fields = "__all__"