Merge pull request 'feature/new-features' (#13) from feature/new-features into master

Reviewed-on: #13
This commit is contained in:
s470631 2021-12-05 16:33:52 +01:00
commit d9da12f26d
53 changed files with 843 additions and 206 deletions

4
.gitignore vendored
View File

@ -134,4 +134,6 @@ GitHub.sublime-settings
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history
.history
secrets.json

8
.idea/.gitignore vendored
View File

@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/

View File

@ -1,30 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="SOITA/settings.py" />
<option name="manageScript" value="$MODULE_DIR$/manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="migrations" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="R User Library" level="project" />
<orderEntry type="library" name="R Skeletons" level="application" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/../SOITA\templates" />
</list>
</option>
</component>
</module>

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM" />
</project>

View File

@ -1,6 +0,0 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8 (2)" project-jdk-type="Python SDK" />
</project>

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/SOITA.iml" filepath="$PROJECT_DIR$/.idea/SOITA.iml" />
</modules>
</component>
</project>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@ -1,126 +0,0 @@
"""
Django settings for SOITA project.
Generated by 'django-admin startproject' using Django 3.2.9.
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
# 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-&bro7o3+h4mu-stibpc_$pen0+b^5t)!thrlj61u9v8_y6ec1)'
# 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',
]
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 = 'SOITA.urls'
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 = 'SOITA.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/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

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'),
),
]

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(trailing_slash=False)
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

View File

@ -1,16 +1,16 @@
"""
ASGI config for SOITA project.
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.2/howto/deployment/asgi/
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', 'SOITA.settings')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_asgi_application()

190
config/settings.py Normal file
View File

@ -0,0 +1,190 @@
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",
"django_extensions",
"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/"

View File

@ -1,7 +1,7 @@
"""SOITA URL Configuration
"""testMe URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
@ -14,8 +14,12 @@ Including another URLconf
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('admin/', admin.site.urls),
path('users/', include("users.urls")),
path('questions/', include("questions.urls")),
path('answers/', include("answers.urls")),
path('tests/', include("trials.urls")),
]

View File

@ -1,16 +1,16 @@
"""
WSGI config for SOITA project.
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.2/howto/deployment/wsgi/
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', 'SOITA.settings')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_wsgi_application()

2
manage.py Normal file → Executable file
View File

@ -6,7 +6,7 @@ import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SOITA.settings')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:

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

@ -0,0 +1,18 @@
# Generated by Django 3.2.9 on 2021-12-05 13:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('questions', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='question',
name='points',
field=models.PositiveSmallIntegerField(default=1),
),
]

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

110
requirements.txt Normal file
View File

@ -0,0 +1,110 @@
alabaster==0.7.12
appdirs==1.4.4
appnope==0.1.2
argon2-cffi==21.1.0
asgiref==3.4.1
attrs==21.2.0
Babel==2.9.1
backcall==0.2.0
bleach==4.1.0
botocore==1.21.15
certifi==2021.10.8
cffi==1.15.0
charset-normalizer==2.0.9
debugpy==1.5.1
decorator==5.1.0
defusedxml==0.7.1
distlib==0.3.2
Django==3.2.9
django-cors-headers==3.10.0
django-debug-toolbar==3.2.2
django-extensions==3.1.5
django-filter==21.1
django-shell-plus==1.1.7
djangorestframework==3.12.4
djangorestframework-simplejwt==5.0.0
docutils==0.17.1
drf-spectacular==0.21.0
entrypoints==0.3
filelock==3.0.12
GDAL==3.3.3
git-remote-codecommit==1.15.1
idna==3.3
imagesize==1.3.0
importlib-metadata==4.8.2
inflection==0.5.1
ipykernel==6.6.0
ipyparallel==8.0.0
ipython==7.30.1
ipython-genutils==0.2.0
ipywidgets==7.6.5
jedi==0.18.1
Jinja2==3.0.3
jmespath==0.10.0
jsonschema==4.2.1
jupyter-client==7.1.0
jupyter-core==4.9.1
jupyterlab-pygments==0.1.2
jupyterlab-widgets==1.0.2
Markdown==3.3.6
MarkupSafe==2.0.1
matplotlib-inline==0.1.3
mistune==0.8.4
nbclient==0.5.9
nbconvert==6.3.0
nbformat==5.1.3
nest-asyncio==1.5.4
nose==1.3.7
notebook==6.4.6
numpy==1.21.4
packaging==21.3
pandocfilters==1.5.0
parso==0.8.3
pbr==5.6.0
pexpect==4.8.0
pickleshare==0.7.5
Pillow==8.4.0
prometheus-client==0.12.0
prompt-toolkit==3.0.23
protobuf==3.17.3
psutil==5.8.0
psycopg2-binary==2.9.2
ptyprocess==0.7.0
pycparser==2.21
Pygments==2.10.0
PyJWT==2.3.0
pyparsing==3.0.6
pyrsistent==0.18.0
python-dateutil==2.8.2
pytz==2021.3
PyYAML==6.0
pyzmq==22.3.0
qtconsole==5.2.1
QtPy==1.11.3
requests==2.26.0
Send2Trash==1.8.0
six==1.16.0
snowballstemmer==2.2.0
Sphinx==4.3.1
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
sqlparse==0.4.2
stevedore==3.3.0
terminado==0.12.1
testpath==0.5.0
tornado==6.1
tqdm==4.62.3
traitlets==5.1.1
uritemplate==4.1.1
urllib3==1.26.6
virtualenv==20.4.7
virtualenv-clone==0.5.4
virtualenvwrapper==4.8.4
wcwidth==0.2.5
webencodings==0.5.1
widgetsnbextension==3.5.2
zipp==3.6.0

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

@ -0,0 +1,18 @@
# Generated by Django 3.2.9 on 2021-12-05 13:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trials', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='test',
name='passing_score',
field=models.PositiveSmallIntegerField(default=0),
),
]

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(default=0)
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

21
users/managers.py Normal file
View File

@ -0,0 +1,21 @@
from django.contrib.auth.base_user import BaseUserManager
from .querysets import UserQuerySet
class UserManager(BaseUserManager):
def get_queryset(self):
return UserQuerySet(self.model, using=self._db)
def create(self, email, password=None, **kwargs):
if password is None:
message = "User must have valid password"
raise ValueError(message)
user = self.model(email=email, **kwargs)
user.set_password(password)
user.save()
return user

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

30
users/models.py Normal file
View File

@ -0,0 +1,30 @@
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
from .managers import UserManager
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"
objects = UserManager()
class Meta:
ordering = ("id", )
def get_details(self):
return {
"first_name": self.first_name,
"last_name": self.last_name,
"email": self.email
}

7
users/querysets.py Normal file
View File

@ -0,0 +1,7 @@
from django.db.models import QuerySet
class UserQuerySet(QuerySet):
def activated(self, **kwargs):
return self.filter(is_activated=True)

26
users/serializers.py Normal file
View File

@ -0,0 +1,26 @@
from rest_framework import serializers
from users.models import User
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
write_only=True,
required=False,
min_length=8,
style={"input_type": "password"},
)
#todo
# avatar = serializers.ImageField(allow_empty_file=True, source="profile.avatar", read_only=True)
class Meta:
model = User
fields = (
"id",
"email",
"first_name",
"last_name",
"is_active",
"password"
)

17
users/urls.py Normal file
View File

@ -0,0 +1,17 @@
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(trailing_slash=False)
router.register("items", UserModelViewSet)
urlpatterns = [
path("", include(router.urls)),
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