Django learning

1.Pycharm community edition creating Django

PyCharm Community Edition How to Create a Django Project and Run \ _ pycharm Community Edition Open django-CSDN Blog

2.Django TemplateDoesNotExist: rest_framework

When we use the djangorestframework framework, we first download the pip install djangorestframework.

Reference blog post Django Template DoesNotExist: rest \ _ framework-CSDN blog

3.Rest \ _ framework mine builds an API

Create a folder with the following three files

Add the following to the views. Py films

# will respond withjsonformat output
from rest_framework.response import Response
# writeapi
from rest_framework.decorators import api_view


# Indicates that the request method isGET
@api_view(['GET'])
def get_data(request):
    goods = {"name": "Test product", "price": 12.3}
    return Response(goods)

Add the following to the URL s. Py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.get_data)
]

Add the following to the URL s. Py of the project

Refresh the browser

You can see

4.Create an application

python manage.py startapp goods 

You can see that there is an application named goods under the directory.

Open the settings. Py file of the project, register the created app, and be sure to add commas, otherwise the data migration will report errors later

Open the models. Py in goods to create the model

from django.db import models


class Goods(models.Model):
    name = models.CharField(max_length=100)
    price = models.FloatField()
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name 

Terminal execution

python manage.py makemigrations
python manage.py migrate

Create a super administrator

python manage.py createsuperuser

Register the model

Restart the service and enter localhost: 8000/admin in the browser to see the following page

Enter the password of the account just registered to add data

5.Data serialization

Create a new serializers. Py in the API folder and add the following

# used to verify data、serialized data、Deserialize data
from rest_framework import serializers
from testD.goods.models import Goods


class GoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = '_all_'
        depth = 1 

Modify views. Py in the API folder.

# will respond withjsonformat output
from rest_framework.response import Response
# writeapi
from rest_framework.decorators import api_view

from testD.api.serializers import GoodsSerializer
from testD.goods.models import Goods


# Indicates that the request method isGET
@api_view(['GET'])
def goods_list(request):
    goods = Goods.objects.all()
    serializer = GoodsSerializer(goods, many=True)
    return Response(goods) 

Modify URL s. Py in the API folder.