This commit is contained in:
Hubert Jankowski 2021-12-05 13:50:34 +01:00
parent b790dfbe0a
commit 539c4690cb
39 changed files with 729 additions and 0 deletions

0
answers/__init__.py Normal file
View File

View File

@ -0,0 +1,29 @@
# Generated by Django 3.1.1 on 2021-12-01 18:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('questions', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Answer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.TextField()),
('is_correct', models.BooleanField(default=False)),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='answers', to='questions.question')),
],
),
migrations.AddConstraint(
model_name='answer',
constraint=models.UniqueConstraint(condition=models.Q(is_correct=True), fields=('question',), name='only_one_correct_answer'),
),
]

View File

27
answers/models.py Normal file
View File

@ -0,0 +1,27 @@
from django.db import models
from django.db.models import Q
from django.db.models import UniqueConstraint
class Answer(models.Model):
question = models.ForeignKey(
"questions.Question",
on_delete=models.CASCADE,
null=False,
related_name="answers"
)
description = models.TextField()
is_correct = models.BooleanField(default=False)
def get_secret_answer(self):
return {
"id": self.id,
"description": self.description,
}
class Meta:
constraints = [UniqueConstraint(
fields=["question"],
condition=Q(is_correct=True),
name="only_one_correct_answer"
)]

14
answers/serializers.py Normal file
View File

@ -0,0 +1,14 @@
from rest_framework import serializers
from answers.models import Answer
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = (
"id",
"description",
"is_correct",
"question"
)

8
answers/urls.py Normal file
View File

@ -0,0 +1,8 @@
from rest_framework.routers import DefaultRouter
from answers.views import AnswerModelViewSet
router = DefaultRouter()
router.register("items", AnswerModelViewSet)
urlpatterns = router.urls

9
answers/views.py Normal file
View File

@ -0,0 +1,9 @@
from rest_framework import viewsets
from answers.models import Answer
from answers.serializers import AnswerSerializer
class AnswerModelViewSet(viewsets.ModelViewSet):
serializer_class = AnswerSerializer
queryset = Answer.objects.all()

0
config/__init__.py Normal file
View File

16
config/asgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
ASGI config for testMe project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_asgi_application()

189
config/settings.py Normal file
View File

@ -0,0 +1,189 @@
import json
import os
"""
Django settings for config project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
secrets = BASE_DIR + "/secrets.json"
with open(secrets) as f:
keys = json.loads(f.read())
def get_secret(setting, keys=keys):
return keys[setting]
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_secret("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = get_secret("DEBUG")
ALLOWED_HOSTS = get_secret("ALLOWED_HOSTS")
# Application definition
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
"django.contrib.gis",
"rest_framework",
"rest_framework_simplejwt",
"users",
"trials",
"answers",
"questions"
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
"corsheaders.middleware.CorsMiddleware",
# "`debug_toolbar.middleware.DebugToolbarMiddleware`",
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = get_secret("ROOT_URLCONF")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': os.path.join(BASE_DIR, "templates"),
'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 = 'config.wsgi.application'
# User model
AUTH_USER_MODEL = "users.User"
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": get_secret("DB_NAME"),
"USER": get_secret("DB_USER"),
"PASSWORD": get_secret("DB_PASSWORD"),
"HOST": get_secret("DB_HOST"),
"PORT": get_secret("DB_PORT"),
}
}
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": (
# "rest_framework.permissions.IsAuthenticated",
),
"DEFAULT_AUTHENTICATION_CLASSES": (
# "rest_framework_simplejwt.authentication.JWTAuthentication",
),
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"DEFAULT_FILTER_BACKENDS": (
"django_filters.rest_framework.DjangoFilterBackend",
"rest_framework.filters.SearchFilter",
"rest_framework.filters.OrderingFilter",
),
"NON_FIELD_ERRORS_KEY": "message",
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '10000/day'
},
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
DEVELOPMENT = get_secret("DEVELOPMENT")
if not DEVELOPMENT:
REST_FRAMEWORK.update({
"DEFAULT_RENDERER_CLASSES": (
"djangorestframework_camel_case.render.CamelCaseJSONRenderer",
"djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer",
),
"DEFAULT_PARSER_CLASSES": (
"djangorestframework_camel_case.parser.CamelCaseJSONParser",
"djangorestframework_camel_case.parser.CamelCaseMultiPartParser",
"djangorestframework_camel_case.parser.CamelCaseFormParser",
),
"JSON_UNDERSCOREIZE": {
"no_underscore_before_number": True,
},
})
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.1/topics/i18n/
LANGUAGE_CODE = "pl"
TIME_ZONE = "Europe/Warsaw"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = "/static/"
MEDIA_ROOT = "/media/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
STATIC_ROOT = os.path.join(BASE_DIR, "../static")
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = ('content-disposition', 'accept-encoding',
'content-type', 'accept', 'origin', 'authorization')
MEDIA_URL = "/media/"

25
config/urls.py Normal file
View File

@ -0,0 +1,25 @@
"""testMe URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/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 include
from django.urls import path
urlpatterns = [
path('users/', include("users.urls")),
path('questions/', include("questions.urls")),
path('answers/', include("answers.urls")),
path('tests/', include("trials.urls")),
]

16
config/wsgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
WSGI config for testMe project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_wsgi_application()

0
questions/__init__.py Normal file
View File

0
questions/apps.py Normal file
View File

View File

@ -0,0 +1,25 @@
# Generated by Django 3.1.1 on 2021-12-01 18:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('trials', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(default='', max_length=200)),
('description', models.TextField()),
('test', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='questions', to='trials.test')),
],
),
]

View File

19
questions/models.py Normal file
View File

@ -0,0 +1,19 @@
from django.db import models
class Question(models.Model):
test = models.ForeignKey(
"trials.Test",
on_delete=models.SET_NULL,
null=True,
related_name="questions"
)
name = models.CharField(max_length=200, default="")
description = models.TextField()
points = models.PositiveSmallIntegerField(default=1)
def get_answers_secret(self):
return [
answer.get_secret_answer()
for answer in self.answers.all()
]

21
questions/serializers.py Normal file
View File

@ -0,0 +1,21 @@
from rest_framework import serializers
from questions.models import Question
class QuestionSerializer(serializers.ModelSerializer):
answers = serializers.SerializerMethodField()
def get_answers(self, instance: Question):
return instance.get_answers_secret()
class Meta:
model = Question
fields = (
"id",
"name",
"description",
"answers",
"test"
)

8
questions/urls.py Normal file
View File

@ -0,0 +1,8 @@
from rest_framework.routers import DefaultRouter
from questions.views import QuestionModelViewSet
router = DefaultRouter()
router.register("items", QuestionModelViewSet)
urlpatterns = router.urls

9
questions/views.py Normal file
View File

@ -0,0 +1,9 @@
from rest_framework import viewsets
from questions.models import Question
from questions.serializers import QuestionSerializer
class QuestionModelViewSet(viewsets.ModelViewSet):
queryset = Question.objects.all()
serializer_class = QuestionSerializer

36
requirements.txt Normal file
View File

@ -0,0 +1,36 @@
appdirs==1.4.4
asgiref==3.4.1
attrs==21.2.0
botocore==1.21.15
distlib==0.3.2
Django==3.2.9
django-cors-headers==3.10.0
django-debug-toolbar==3.2.2
django-filter==21.1
djangorestframework==3.12.4
djangorestframework-simplejwt==5.0.0
drf-spectacular==0.21.0
filelock==3.0.12
GDAL==3.3.3
git-remote-codecommit==1.15.1
inflection==0.5.1
jmespath==0.10.0
jsonschema==4.2.1
numpy==1.21.4
pbr==5.6.0
Pillow==8.4.0
protobuf==3.17.3
psycopg2-binary==2.9.2
PyJWT==2.3.0
pyrsistent==0.18.0
python-dateutil==2.8.2
pytz==2021.3
PyYAML==6.0
six==1.16.0
sqlparse==0.4.2
stevedore==3.3.0
uritemplate==4.1.1
urllib3==1.26.6
virtualenv==20.4.7
virtualenv-clone==0.5.4
virtualenvwrapper==4.8.4

View File

@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ test.name }}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
.test_title {
font-size: 40px;
}
.test_body {
width: 50%;
}
.question_title {
font-size: 20px;
}
</style>
</head>
<body>
<div class="card">
<div class="card-body test_body">
<div class="card-header test_title">
{{ test.name }}
</div>
{% for question in test.questions.all %}
<div class="question_title">
{{ question.description }}
</div>
<div class="list-group">
{% for answer in question.answers.all %}
<label class="list-group-item">
<input class="form-check-input me-1" type="radio" name={{ question.id }} value="">
{{ answer.description }}
</label>
{% endfor %}
</div>
{% endfor %}
</div>
</div>
</body>
</html>

0
trials/__init__.py Normal file
View File

0
trials/apps.py Normal file
View File

View File

@ -0,0 +1,21 @@
# Generated by Django 3.1.1 on 2021-12-01 18:52
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Test',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
]

View File

26
trials/models.py Normal file
View File

@ -0,0 +1,26 @@
from django.db import models
class Test(models.Model):
name = models.CharField(max_length=100)
passing_score = models.PositiveSmallIntegerField()
def get_score(self, answers):
"""
[
{
"question": 1,
"answer": 1
},
{
"question": 2,
"answer": 1
}
]
"""
points = 0
for answer in answers:
question = self.questions.get(id=answer["question"])
if question.answers.get(id=answer["answer"]).is_correct:
points += question.points
return points

18
trials/serializers.py Normal file
View File

@ -0,0 +1,18 @@
from rest_framework import serializers
from questions.serializers import QuestionSerializer
from trials.models import Test
class TestSerializer(serializers.ModelSerializer):
questions = QuestionSerializer(many=True, required=False)
class Meta:
model = Test
fields = (
"id",
"name",
"passing_score",
"questions"
)

16
trials/urls.py Normal file
View File

@ -0,0 +1,16 @@
from django.urls import path
from rest_framework.routers import DefaultRouter
from trials.views import TestModelViewSet
from trials.views import TestTemplateView
from trials.views import TestValidateAPIView
router = DefaultRouter()
router.register("items", TestModelViewSet)
urlpatterns = [
path('<int:test_id>/show/', TestTemplateView.as_view()),
path('<int:test_id>/mark/', TestValidateAPIView.as_view())
]
urlpatterns += router.urls

50
trials/views.py Normal file
View File

@ -0,0 +1,50 @@
from django.views.generic import TemplateView
from rest_framework import views
from rest_framework import viewsets
from rest_framework.response import Response
from config.settings import BASE_DIR
from trials.models import Test
from trials.serializers import TestSerializer
class TestModelViewSet(viewsets.ModelViewSet):
queryset = Test.objects.all()
serializer_class = TestSerializer
class TestTemplateView(TemplateView):
permission_classes = []
template_name = BASE_DIR + f"/templates/generic_test.html"
def get_queryset(self):
return Test.objects.all()
def get_context_data(self, test_id, **kwargs):
context = super().get_context_data(**kwargs)
context["test"] = self.get_queryset().filter(id=test_id).prefetch_related("questions__answers").first()
return context
class TestValidateAPIView(views.APIView):
PASSED = "passed"
FAILED = "failed"
UNKNOWN = "unknown"
PASSED = {
True: PASSED,
False: FAILED
}
def get_score(self, test: Test, answers):
return test.get_score(answers)
def post(self, request, test_id, **kwargs):
test = Test.objects.get(id=test_id)
score = self.get_score(test, request.data["answers"])
status = score >= test.passing_score
return Response({
"status": self.PASSED.get(status, self.UNKNOWN),
"points": score
})

BIN
users/.DS_Store vendored Normal file

Binary file not shown.

0
users/__init__.py Normal file
View File

BIN
users/migrations/.DS_Store vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,32 @@
# Generated by Django 3.1.1 on 2021-12-01 18:52
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('first_name', models.CharField(max_length=100)),
('last_name', models.CharField(max_length=100)),
('email', models.EmailField(db_index=True, max_length=50, unique=True)),
('is_active', models.BooleanField(default=False)),
('confirmation_number', models.CharField(max_length=100)),
('reset_code', models.CharField(max_length=100)),
('avatar', models.ImageField(null=True, upload_to='avatars/')),
],
options={
'ordering': ('id',),
},
),
]

View File

26
users/models.py Normal file
View File

@ -0,0 +1,26 @@
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
class User(AbstractBaseUser):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(db_index=True, unique=True, max_length=50)
is_active = models.BooleanField(default=False)
confirmation_number = models.CharField(max_length=100)
reset_code = models.CharField(max_length=100)
avatar = models.ImageField(upload_to="avatars/", null=True)
USERNAME_FIELD = "email"
class Meta:
ordering = ("id", )
def get_details(self):
return {
"first_name": self.first_name,
"last_name": self.last_name,
"email": self.email
}

16
users/serializers.py Normal file
View File

@ -0,0 +1,16 @@
from rest_framework import serializers
from users.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
"id",
"email",
"first_name",
"last_name",
"is_active",
"password"
)

16
users/urls.py Normal file
View File

@ -0,0 +1,16 @@
from rest_framework.routers import DefaultRouter
from django.urls import include
from django.urls import path
from users.views import UserModelViewSet
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.views import TokenRefreshView
router = DefaultRouter()
router.register("items", UserModelViewSet)
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

9
users/views.py Normal file
View File

@ -0,0 +1,9 @@
from rest_framework import viewsets
from users.models import User
from users.serializers import UserSerializer
class UserModelViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer