一个简单的 Model
在 Django 中,模型用来存储和组织数据,每个模型包含了你的数据的字段和一些行为。
它也包括了数据迁移(migration),也就是从你的模型的文件生成相应的数据库表。
修改了模型文件后会生成新的迁移文件,同时保留历史迁移文件。
下面是官方的例子:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
简单的视图
在auth/views.py
中添加
from django.views.generic import View
class IndexView(View):
def get(self, request):
return render(request, 'index.html')
例如项目叫 sample,在 sample/urls.py
中修改如下:
from django.contrib import admin
from django.urls import include, path
from auth.views import IndexView
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('auth.urls')),
path('', IndexView.as_view(), name='index')
]
这样当我们访问首页时,视图就会渲染index.html
,并呈现给我们。
静态文件的配置
我们的模板中有时需要使用一些静态的 css、js 或者图片,因此我们需要配置静态文件的路径。
在 settings.py 中,找到STATIC_URL
所在的位置,改为如下:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'templates', 'static'), # 静态文件存放在项目根目录下的 templates/static/
]
STATIC_URL = '/static/' #静态文件的 URL 路径
STATIC_ROOT = os.path.join(BASE_DIR, 'static') # 项目部署时,执行 collectstatic 时要将文件存放到的路径
然后修改 urls.py :
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
# ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)