## page was renamed from DjangoREST = Django REST framework = * https://www.django-rest-framework.org/ Django REST framework is a powerful and flexible toolkit for building Web APIs. == Quickstart == * Check [[https://github.com/vborrego/django-rest-test|django-rest-test]] * django shell ```python3 manage.py shell``` * Based on https://www.django-rest-framework.org/tutorial/quickstart/#quickstart * https://www.django-rest-framework.org/api-guide/viewsets/ * https://www.django-rest-framework.org/api-guide/views/ {{{#!highlight bash cd ~/tmp mkdir django-rest-test cd django-rest-test sudo apt install python3-venv python3 -m venv virtenv . virtenv/bin/activate pip install djangorestframework find . virtenv/ django-admin startproject tutorial . cd tutorial django-admin startapp quickstart cd .. python manage.py migrate # sync DB python manage.py createsuperuser --email admin@example.com --username admin # create super user, pwd: 12345678 nano tutorial/quickstart/serializers.py nano tutorial/quickstart/views.py nano tutorial/urls.py nano tutorial/settings.py nano tutorials/quickstart/apps.py nano tutorials/quickstart/models.py python manage.py runserver # Starting development server at http://127.0.0.1:8000/ curl -H 'Accept: application/json; indent=4' -u admin:12345678 http://127.0.0.1:8000/users/ sqlite3 db.sqlite3 .tables select * from auth_user; .exit python3 manage.py collectstatic mkdir -p static/others echo "aaaa" > static/others/test.txt curl -H 'Accept: application/json' -u admin:1234567 http://127.0.0.1:8000/helloworld/ curl -H 'Accept: application/json' -u admin:12345678 http://127.0.0.1:8000/helloworldanon/ curl http://127.0.0.1:8000/helloworldviewset/ curl http://127.0.0.1:8000/static/others/test.txt curl -X POST -H "Content-Type:application/json" -u admin:12345678 -d "{\"task\":\"t2\"}" http://127.0.0.1:8000/tasks/ }}} === tutorials/quickstart/apps.py === {{{#!highlight python from django.apps import AppConfig class QuickstartConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'tutorial.quickstart' }}} === tutorials/quickstart/models.py === {{{#!highlight python from django.db import models class Task(models.Model): created = models.DateTimeField(auto_now_add=True) task = models.CharField(max_length=128, blank=True, default='') """ python manage.py makemigrations quickstart python manage.py migrate sqlite3 db.sqlite3 .tables # quickstart_task .dump quickstart_task PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS "quickstart_task" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "created" datetime NOT NULL, "task" varchar(128) NOT NULL); COMMIT; .exit """ }}} === tutorial/quickstart/serializers.py === {{{#!highlight python from django.contrib.auth.models import User, Group from rest_framework import serializers from tutorial.quickstart.models import Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url', 'name'] class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['id','task','created'] }}} === tutorial/quickstart/views.py === {{{#!highlight python import json from django.contrib.auth.models import User, Group from rest_framework import viewsets,permissions from tutorial.quickstart.serializers import UserSerializer, GroupSerializer from django.views.decorators.csrf import csrf_exempt from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.views import APIView from tutorial.quickstart.models import Task from tutorial.quickstart.serializers import TaskSerializer from django.http import HttpResponse, JsonResponse from rest_framework.parsers import JSONParser class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] @csrf_exempt @api_view(['GET']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def hello_world(request): """ Function view """ return Response({"message": "Hello world", "user": str(request.user)}) class HelloWorldAnonView(APIView): def get(self, request, format=None): return Response({"message": "Hello world anonymous", "user": str(request.user)}) class HelloWorldViewSet(viewsets.ViewSet): # authentication required permission_classes = [permissions.IsAuthenticated] def list(self, request): return Response({"message": "Hello world view set up and running " + str(request.user)}) class TaskViewSet(viewsets.ModelViewSet): # ModelViewSet queryset = Task.objects.all().order_by("created") serializer_class = TaskSerializer permission_classes = [permissions.IsAuthenticated] # # authentication required # permission_classes = [permissions.IsAuthenticated] # def list(self, request): # serializer = TaskSerializer(Task.objects.all(), many=True) # return Response(serializer.data) # def create(self, request): # payload = JSONParser().parse(request) # serializer = TaskSerializer(data=payload) # if serializer.is_valid(): # serializer.save() # return Response(serializer.data, status=201) }}} === tutorial/urls.py === {{{#!highlight python from django.urls import include, path from rest_framework import routers from tutorial.quickstart import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) router.register(r'helloworldviewset', views.HelloWorldViewSet,basename="helloworldviewset") router.register(r'tasks', views.TaskViewSet,basename="tasks") # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('helloworld/',views.hello_world), path('helloworldanon/',views.HelloWorldAnonView.as_view()), ] }}} === tutorial/settings.py === {{{#!highlight python """ Django settings for tutorial project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j8vs^2rq97)%g%v4fk-nl(3pho4ve)=6%&$**0++$p%v514r8r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'tutorial.quickstart.apps.QuickstartConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tutorial.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'tutorial.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( ("others", os.path.join(STATIC_ROOT,'others')), ) # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } }}} == Queryset == * https://docs.djangoproject.com/en/3.2/ref/models/querysets/#queryset-api-reference == Foreign keys and related names, _set == Instance members in model instances are created based on identified relations. Usually those members end with _set. * https://docs.djangoproject.com/en/3.2/ref/models/fields/#foreignkey {{{ A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option. }}} * https://docs.djangoproject.com/en/3.2/topics/db/models/#be-careful-with-related-name-and-related-query-name {{{ If you don’t specify a related_name attribute for a field in an abstract base class, the default reverse name will be the name of the child class followed by '_set', just as it normally would be if you’d declared the field directly on the child class. For example, in the above code, if the related_name attribute was omitted, the reverse name for the m2m field would be childa_set in the ChildA case and childb_set for the ChildB field. }}} == Related manager == * https://docs.djangoproject.com/en/3.2/ref/models/relations/#related-objects-reference A “related manager” is a manager used in a one-to-many or many-to-many related context.