创建一个Django项目

步骤 1: 创建 Django 项目和应用
创建 Django 项目:

bash
django-admin startproject myproject
cd myproject
创建 Django 应用:

bash
python manage.py startapp myapp
安装并配置 Django Rest Framework(如果尚未安装):

bash
pip install djangorestframework
将 myapp 和 rest_framework 添加到 settings.py 的 INSTALLED_APPS 中:

python
INSTALLED_APPS = [
...
'myapp',
'rest_framework',
]
步骤 2: 创建模型
在 myapp/models.py 中定义一个模型来存储数据:

python
from django.db import models

class DataEntry(models.Model):
zhaopin = models.DateField()
jyyc = models.DateField()
xzcf = models.DateField()
zl = models.DateField()
sb = models.DateField()
jzzz = models.DateField()
cpws = models.DateField()
fygg = models.DateField()
ktgg = models.DateField()
laxx = models.DateField()
zbaj = models.DateField()
bzxr = models.DateField()
sxbzxr = models.DateField()
xzgxf = models.DateField()
yzwf = models.DateField()
pcxx = models.DateField()
ztb = models.DateField()

def __str__(self):
    return f'Entry {self.id}'

步骤 3: 数据迁移
运行以下命令创建数据库表:

bash
python manage.py makemigrations
python manage.py migrate
步骤 4: 导入数据
在 Django shell 中插入数据:

bash
python manage.py shell
然后执行以下代码:

python
import json
from myapp.models import DataEntry

data = {
"zhaopin":"2024-09-11","jyyc":"2024-09-08","xzcf":"2024-09-09",
"zl":"2024-09-06","sb":"2024-08-27","jzzz":"2024-09-11",
"cpws":"2024-09-02","fygg":"2024-09-07","ktgg":"2024-09-11",
"laxx":"2024-09-07","zbaj":"2024-09-05","bzxr":"2024-09-07",
"sxbzxr":"2024-09-06","xzgxf":"2024-09-06","yzwf":"2024-09-04",
"pcxx":"2024-09-07","ztb":"2024-09-06"
}

entry = DataEntry(**data)
entry.save()
步骤 5: 创建API视图
在 myapp/views.py 中创建一个 API 视图:

python
from rest_framework import generics
from .models import DataEntry
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import DataEntrySerializer

class DataEntryList(generics.ListAPIView):
queryset = DataEntry.objects.all()
serializer_class = DataEntrySerializer

@api_view(['GET'])
def get_data(request):
data_entries = DataEntry.objects.all()
serializer = DataEntrySerializer(data_entries, many=True)
return Response(serializer.data)
步骤 6: 创建序列化器
在 myapp/serializers.py 中添加序列化器:

python
from rest_framework import serializers
from .models import DataEntry

class DataEntrySerializer(serializers.ModelSerializer):
class Meta:
model = DataEntry
fields = 'all'
步骤 7: 配置 URL 路由
在 myapp/urls.py 中定义 URL 路由:

python
from django.urls import path
from .views import DataEntryList, get_data

urlpatterns = [
path('data/', DataEntryList.as_view(), name='data-entry-list'),
]
同时在 myproject/urls.py 中包含应用的 URLs:

python
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
]
步骤 8: 创建前端页面
在 `myapp/templates/my

posted @ 2024-09-13 18:11  sriver_dl  Views(16)  Comments(0Edit  收藏  举报