data, migrations, drf customizations

This commit is contained in:
Tyrel Souza 2019-09-15 20:32:42 -04:00
parent 7bdf89948f
commit f40d4ea281
No known key found for this signature in database
GPG Key ID: 5A9394D4C30AEAC0
14 changed files with 406 additions and 147 deletions

View File

@ -1,17 +1,26 @@
from django.contrib import admin
from flight.models import Flight, Plane, Airport
# Register your models here.
class FlightAdmin(admin.ModelAdmin):
pass
admin.site.register(Flight, FlightAdmin)
class PlaneAdmin(admin.ModelAdmin):
pass
admin.site.register(Plane, PlaneAdmin)
class AirportAdmin(admin.ModelAdmin):
pass
admin.site.register(Airport, AirportAdmin)

15
logbook/flight/api.py Normal file
View File

@ -0,0 +1,15 @@
from rest_framework import routers
from django.urls import path, include
from flight import views
router = routers.DefaultRouter()
router.register(r"flights", views.FlightViewSet)
router.register(r"planes", views.PlaneViewSet)
router.register(r"airports", views.AirportViewSet)
# 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")),
]

View File

@ -2,4 +2,4 @@ from django.apps import AppConfig
class FlightConfig(AppConfig):
name = 'flight'
name = "flight"

View File

@ -9,48 +9,135 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
]
dependencies = []
operations = [
migrations.CreateModel(
name='Airport',
name="Airport",
fields=[
('icao', models.CharField(max_length=4, primary_key=True, serialize=False)),
(
"icao",
models.CharField(max_length=4, primary_key=True, serialize=False),
)
],
),
migrations.CreateModel(
name='Plane',
name="Plane",
fields=[
('tail_number', models.CharField(max_length=64, primary_key=True, serialize=False)),
('name', models.CharField(max_length=64)),
('manufacturer', models.CharField(max_length=64)),
('model', models.CharField(max_length=64)),
(
"tail_number",
models.CharField(max_length=64, primary_key=True, serialize=False),
),
("name", models.CharField(max_length=64)),
("manufacturer", models.CharField(max_length=64)),
("model", models.CharField(max_length=64)),
],
),
migrations.CreateModel(
name='Flight',
name="Flight",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('flight_date', models.DateField()),
('instructor', models.CharField(blank=True, max_length=64)),
('remarks', models.TextField(blank=True)),
('landings', models.IntegerField()),
('airplane_sel_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('airplane_mel_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('cross_country_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('day_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('night_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('actual_instrument_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('simulated_instrument_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('ground_trainer_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('dual_received_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('pilot_in_command_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('total_time', models.DecimalField(decimal_places=1, default=Decimal('0'), max_digits=2)),
('link', models.CharField(blank=True, max_length=200)),
('airport_arrive', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='flight_to', to='flight.Airport')),
('airport_depart', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='flight_from', to='flight.Airport')),
('plane', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='flight.Plane')),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("flight_date", models.DateField()),
("instructor", models.CharField(blank=True, max_length=64)),
("remarks", models.TextField(blank=True)),
("landings", models.IntegerField()),
(
"airplane_sel_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"airplane_mel_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"cross_country_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"day_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"night_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"actual_instrument_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"simulated_instrument_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"ground_trainer_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"dual_received_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"pilot_in_command_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
(
"total_time",
models.DecimalField(
decimal_places=1, default=Decimal("0"), max_digits=2
),
),
("link", models.CharField(blank=True, max_length=200)),
(
"airport_arrive",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="flight_to",
to="flight.Airport",
),
),
(
"airport_depart",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="flight_from",
to="flight.Airport",
),
),
(
"plane",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT, to="flight.Plane"
),
),
],
),
]

View File

@ -0,0 +1,21 @@
# Generated by Django 2.2.5 on 2019-09-15 23:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("flight", "0001_initial")]
operations = [
migrations.AddField(
model_name="airport",
name="link",
field=models.CharField(blank=True, max_length=256),
),
migrations.AddField(
model_name="plane",
name="engine_count",
field=models.IntegerField(default=1),
),
]

View File

@ -0,0 +1,14 @@
# Generated by Django 2.2.5 on 2019-09-15 23:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("flight", "0002_auto_20190915_2353")]
operations = [
migrations.AddField(
model_name="flight", name="leg", field=models.IntegerField(default=0)
)
]

View File

@ -0,0 +1,26 @@
# Generated by Django 2.2.5 on 2019-09-16 00:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("flight", "0003_flight_leg"),
]
operations = [
migrations.AddField(
model_name="flight",
name="user",
field=models.ForeignKey(
default=1,
on_delete=django.db.models.deletion.PROTECT,
to=settings.AUTH_USER_MODEL,
),
preserve_default=False,
)
]

View File

@ -1,46 +1,87 @@
from django.db import models
from django.contrib.auth.models import User
from decimal import Decimal
# Create your models here.
class Plane(models.Model):
tail_number = models.CharField(max_length=64, primary_key=True) # "N43337"
name = models.CharField(max_length=64) # "Warrior II"
manufacturer = models.CharField(max_length=64) # Piper
model = models.CharField(max_length=64) # PA28-151
name = models.CharField(max_length=64) # "Warrior II"
manufacturer = models.CharField(max_length=64) # Piper
model = models.CharField(max_length=64) # PA28-151
engine_count = models.IntegerField(default=1)
def __str__ (self):
def __str__(self):
return self.tail_number
class Airport(models.Model):
icao = models.CharField(max_length=4, primary_key=True)
link = models.CharField(max_length=256, blank=True)
def __str__ (self):
def __str__(self):
return self.icao
class Flight(models.Model):
flight_date = models.DateField() # "flight_date": "2019-08-31",
plane = models.ForeignKey(Plane, on_delete=models.PROTECT)
instructor = models.CharField(max_length=64, blank=True) # "instructor": "Gene Moody",
remarks = models.TextField(blank=True) # "remarks": "normal to/l, shortfield to/l, std turns, constant speed, constant descents",
airport_depart = models.ForeignKey(Airport, on_delete=models.PROTECT, related_name='%(class)s_from') # "from": "KEEN",
airport_arrive = models.ForeignKey(Airport, on_delete=models.PROTECT, related_name='%(class)s_to') # "to": "KEEN",
class Flight(models.Model):
flight_date = models.DateField() # "flight_date": "2019-08-31",
plane = models.ForeignKey(Plane, on_delete=models.PROTECT)
airport_depart = models.ForeignKey(
Airport, on_delete=models.PROTECT, related_name="%(class)s_from"
) # "from": "KEEN",
airport_arrive = models.ForeignKey(
Airport, on_delete=models.PROTECT, related_name="%(class)s_to"
) # "to": "KEEN",
user = models.ForeignKey(User, on_delete=models.PROTECT)
instructor = models.CharField(
max_length=64, blank=True
) # "instructor": "Gene Moody",
remarks = models.TextField(
blank=True
) # "remarks": "normal to/l, shortfield to/l, std turns, constant speed, constant descents",
landings = models.IntegerField()
airplane_sel_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
airplane_mel_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
cross_country_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
airplane_sel_time = models.DecimalField(
max_digits=2, decimal_places=1, default=Decimal(0.0)
)
airplane_mel_time = models.DecimalField(
max_digits=2, decimal_places=1, default=Decimal(0.0)
)
cross_country_time = models.DecimalField(
max_digits=2, decimal_places=1, default=Decimal(0.0)
)
day_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
night_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
actual_instrument_time = models.DecimalField(decimal_places=1,max_digits=2, default=Decimal(0.0))
simulated_instrument_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
ground_trainer_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
dual_received_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
pilot_in_command_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
total_time = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
night_time = models.DecimalField(
max_digits=2, decimal_places=1, default=Decimal(0.0)
)
actual_instrument_time = models.DecimalField(
decimal_places=1, max_digits=2, default=Decimal(0.0)
)
simulated_instrument_time = models.DecimalField(
max_digits=2, decimal_places=1, default=Decimal(0.0)
)
ground_trainer_time = models.DecimalField(
max_digits=2, decimal_places=1, default=Decimal(0.0)
)
dual_received_time = models.DecimalField(
max_digits=2, decimal_places=1, default=Decimal(0.0)
)
pilot_in_command_time = models.DecimalField(
max_digits=2, decimal_places=1, default=Decimal(0.0)
)
total_time = models.DecimalField(
max_digits=2, decimal_places=1, default=Decimal(0.0)
)
link = models.CharField(max_length=200, blank=True)
leg = models.IntegerField(default=0)
def __str__(self):
return f"{self.flight_date}: {self.plane} {self.total_time}h - {self.airport_depart} -> {self.airport_arrive}"
return f"{self.flight_date}: {self.plane} {self.total_time}h - {self.airport_depart} -> {self.airport_arrive}"

View File

@ -0,0 +1,46 @@
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from flight.models import Flight, Plane, Airport
class PlaneSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Plane
fields = ["tail_number", "name", "manufacturer", "model", "engine_count"]
class AirportSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Airport
fields = ["icao", "link"]
class FlightSerializer(serializers.HyperlinkedModelSerializer):
plane = serializers.StringRelatedField()
airport_depart = serializers.StringRelatedField()
airport_arrive = serializers.StringRelatedField()
class Meta:
model = Flight
fields = [
"flight_date",
"plane",
"instructor",
"remarks",
"airport_depart",
"airport_arrive",
"landings",
"airplane_sel_time",
"airplane_mel_time",
"cross_country_time",
"day_time",
"night_time",
"actual_instrument_time",
"simulated_instrument_time",
"ground_trainer_time",
"dual_received_time",
"pilot_in_command_time",
"total_time",
"leg",
"link",
]

View File

@ -1,3 +1,18 @@
from django.shortcuts import render
from rest_framework import viewsets
from flight.serializers import PlaneSerializer, AirportSerializer, FlightSerializer
from flight.models import Flight, Plane, Airport
# Create your views here.
class PlaneViewSet(viewsets.ModelViewSet):
queryset = Plane.objects.all().order_by("tail_number")
serializer_class = PlaneSerializer
class AirportViewSet(viewsets.ModelViewSet):
queryset = Airport.objects.all().order_by("icao")
serializer_class = AirportSerializer
class FlightViewSet(viewsets.ModelViewSet):
queryset = Flight.objects.all().order_by("-flight_date")
serializer_class = FlightSerializer

View File

@ -9,7 +9,7 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$a!s6tai*f#n2uklhefwaio)%o+a-39n64kyuep0*0-*^yq+xw'
SECRET_KEY = "$a!s6tai*f#n2uklhefwaio)%o+a-39n64kyuep0*0-*^yq+xw"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
@ -20,61 +20,60 @@ 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',
'rest_framework.authtoken',
'corsheaders',
'flight',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"rest_framework.authtoken",
"corsheaders",
"flight",
]
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',
'corsheaders.middleware.CorsMiddleware',
"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",
"corsheaders.middleware.CorsMiddleware",
]
ROOT_URLCONF = 'logbook.urls'
ROOT_URLCONF = "logbook.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',
],
"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 = 'logbook.wsgi.application'
WSGI_APPLICATION = "logbook.wsgi.application"
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'logbook',
'USER': os.environ.get('DJANGO_DB_NAME', ''),
'PASSWORD': os.environ.get('DJANGO_DB_PASS', ''),
'HOST': '127.0.0.1',
'PORT': '5433',
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "logbook",
"USER": os.environ.get("DJANGO_DB_NAME", ""),
"PASSWORD": os.environ.get("DJANGO_DB_PASS", ""),
"HOST": "127.0.0.1",
"PORT": "5433",
}
}
@ -84,26 +83,20 @@ DATABASES = {
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',
"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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"
TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"
USE_I18N = True
@ -115,39 +108,41 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_URL = "/static/"
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
# TODO - set this properly for production
'http://127.0.0.1:8080',
'http://127.0.0.1:8000',
"http://127.0.0.1:8080",
"http://127.0.0.1:8000",
"http://127.0.0.1:8001",
"http://127.0.0.1:8081",
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
"DEFAULT_PERMISSION_CLASSES": (
# By default we set everything to admin,
# then open endpoints on a case-by-case basis
'rest_framework.permissions.IsAdminUser',
"rest_framework.permissions.IsAdminUser",
),
'TEST_REQUEST_RENDERER_CLASSES': (
'rest_framework.renderers.MultiPartRenderer',
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.TemplateHTMLRenderer'
"TEST_REQUEST_RENDERER_CLASSES": (
"rest_framework.renderers.MultiPartRenderer",
"rest_framework.renderers.JSONRenderer",
"rest_framework.renderers.TemplateHTMLRenderer",
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_jwt.authentication.JSONWebTokenAuthentication",
"rest_framework.authentication.SessionAuthentication",
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 20,
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 20,
}
JWT_AUTH = {
'JWT_ALLOW_REFRESH': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1),
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
}
"JWT_ALLOW_REFRESH": True,
"JWT_EXPIRATION_DELTA": datetime.timedelta(hours=1),
"JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=7),
}

View File

@ -1,21 +1,11 @@
"""logbook URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, include
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
urlpatterns = [
path('admin/', admin.site.urls),
path("admin/", admin.site.urls),
path("api/v1/auth/obtain_token/", obtain_jwt_token),
path("api/v1/auth/refresh_token/", refresh_jwt_token),
# The rest of the endpoints
path("api/v1/", include("flight.api")),
]

View File

@ -11,6 +11,6 @@ import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'logbook.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "logbook.settings")
application = get_wsgi_application()

View File

@ -5,7 +5,7 @@ import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'logbook.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "logbook.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
@ -17,5 +17,5 @@ def main():
execute_from_command_line(sys.argv)
if __name__ == '__main__':
if __name__ == "__main__":
main()