django

遗失の心跳 / 2023-06-11 / 原文

1 常用指令

pip install django -i https://pypi.douban.com/simple/ # 使用豆瓣镜像安装 django
pip install djangorestframework # 安装 drf
django-admin startproject mysite # 创建个人项目
python manage.py runserver # 启动项目
python manage.py startapp polls # 创建投票应用
python manage.py makemigrations # 生成数据库迁移文件
python manage.py migrate # 执行数据库迁移文件
python manage.py createsuperuser # 创建超级账号

2 编写第一个视图

# polls.views

from django.http import HttpResponse


def index(request):
    return HttpResponse("你好,欢迎来到投票网站")

# polls.urls

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
]

# mysite.urls

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path("polls/", include("polls.urls")),
]

访问:http://127.0.0.1:8000/polls/
image

3 创建 model 类并生成数据库表

# polls.models

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)

执行:

python manage.py makemigrations # 生成数据库迁移文件
python manage.py migrate # 执行数据库迁移文件

使用 shell 命令查看效果:

python manage.py shell # 打开shell 窗口
from polls.models import Choice, Question
Question.objects.all()
# <QuerySet []>
 q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id
# 1
Question.objects.all()
# <QuerySet [<Question: Question object (1)>]>

但是 <QuerySet [<Question: Question object (1)>]>= 好像并没有实际意义,所以可以给 model 加上 __str__ 方法:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")

    def __str__(self):
        return self.question_text

4 创建超级账号

python manage.py createsuperuser

登录:
http://127.0.0.1:8000/admin/
image
在管理页中加入投票模块:

# polls.admin

from django.contrib import admin

from .models import Question

admin.site.register(Question)

再次访问管理页:
image

5 使用 drf

Serializers:

from .models import Question
from rest_framework import serializers


class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = ['question_text', 'pub_date']

Views:

from .serializers import QuestionSerializer
from rest_framework import viewsets

class QuestionViewSet(viewsets.ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

URLs:

from rest_framework import routers
from . import views
from django.urls import include, path

router = routers.DefaultRouter()

router.register(r'drf-question', views.QuestionViewSet)

urlpatterns = [
    path('', include(router.urls)),  # 使用router路由
]

6 类视图

Views:

from rest_framework.views import APIView
from django.contrib.auth.models import User


class ListUsers(APIView):
    def get(self, request):
        usernames = [user.username for user in User.objects.all()]
        print(usernames)  # ['admin']
        return Response(usernames)

URLs:

urlpatterns = [
    path('', include(router.urls)),
    path('cbv-user', views.ListUsers.as_view())
]

image

7 权限管理

https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html
settings:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

urls:

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    ...
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]