diff --git a/.flake8 b/.flake8 deleted file mode 100644 index edb71ad5..00000000 --- a/.flake8 +++ /dev/null @@ -1,5 +0,0 @@ -[flake8] -ignore = E203, E266, W503 -max-line-length = 79 -max-complexity = 18 -select = B,C,E,F,W,T4,B9 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml deleted file mode 100644 index 09fa111a..00000000 --- a/.github/workflows/test.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: Test - -on: - pull_request: - branches: - - "master" - -jobs: - test: - runs-on: ubuntu-latest - timeout-minutes: 10 - - steps: - - name: Checkout repo - uses: actions/checkout@v2 - - - name: Set Up Python 3.8 - uses: actions/setup-python@v2 - with: - python-version: 3.8 - - - name: Install pytest and flake8 - run: | - python -m pip install --upgrade pip - pip install -r requirements.txt - - - name: Run flake8 - run: flake8 app/ - - - name: Run tests - timeout-minutes: 5 - run: pytest tests/ - diff --git a/README.md b/README.md index 5be5cadc..54cc298a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,14 @@ -# Python boilerplate for GitHub tasks +# Taxi service authentication - Read [the guideline](https://github.com/mate-academy/py-task-guideline/blob/main/README.md) before start -- Implement the task described [here](app/main.py) + +In this task, you will implement a visit counter, login/logout functionality, and make your site available only +authenticated users. + +1. Implement a visit counter on the home screen. It should show how many times a user visited the home page before. + +2. Create login/logout screens. Provide authentication to your project using built-in Django authentication. + +3. Display the username on the top of the sidebar and login/logout button depending on if the user is authenticated. + +4. Protect all your views from unauthenticated users using `login_required` decorator and `LoginRequiredMixin`. diff --git a/app/main.py b/app/main.py deleted file mode 100644 index 773a588b..00000000 --- a/app/main.py +++ /dev/null @@ -1,3 +0,0 @@ -# TODO: add initial code -def hello_world(): - return "Hello, world!" diff --git a/manage.py b/manage.py new file mode 100755 index 00000000..e6082a24 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "taxi_service.settings") + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt index 7c8a737c..57ac677c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1 @@ -pytest==6.2.5 -flake8==4.0.1 \ No newline at end of file +django==4.0.2 \ No newline at end of file diff --git a/static/css/styles.css b/static/css/styles.css new file mode 100644 index 00000000..1d8a1b3d --- /dev/null +++ b/static/css/styles.css @@ -0,0 +1,3 @@ +body { + margin-top: 20px; +} diff --git a/tests/__init__.py b/taxi/__init__.py similarity index 100% rename from tests/__init__.py rename to taxi/__init__.py diff --git a/taxi/admin.py b/taxi/admin.py new file mode 100644 index 00000000..01ed860b --- /dev/null +++ b/taxi/admin.py @@ -0,0 +1,23 @@ +from django.contrib import admin +from django.contrib.auth.admin import UserAdmin +from .models import Driver, Car, Manufacturer + + +@admin.register(Driver) +class DriverAdmin(UserAdmin): + list_display = UserAdmin.list_display + ("license_number",) + fieldsets = UserAdmin.fieldsets + ( + (("Additional info", {"fields": ("license_number",)}),) + ) + add_fieldsets = UserAdmin.add_fieldsets + ( + (("Additional info", {"fields": ("first_name", "last_name", "license_number",)}),) + ) + + +@admin.register(Car) +class CarAdmin(admin.ModelAdmin): + search_fields = ("model",) + list_filter = ("manufacturer",) + + +admin.site.register(Manufacturer) diff --git a/taxi/apps.py b/taxi/apps.py new file mode 100644 index 00000000..5e913a32 --- /dev/null +++ b/taxi/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class TaxiConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "taxi" diff --git a/taxi/migrations/0001_initial.py b/taxi/migrations/0001_initial.py new file mode 100644 index 00000000..ff29293e --- /dev/null +++ b/taxi/migrations/0001_initial.py @@ -0,0 +1,63 @@ +# Generated by Django 4.0.2 on 2022-03-24 06:38 + +from django.conf import settings +import django.contrib.auth.models +import django.contrib.auth.validators +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0012_alter_user_first_name_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='Driver', + fields=[ + ('id', models.BigAutoField(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')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), + ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), + ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), + ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), + ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), + ('license_number', models.CharField(max_length=255)), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name': 'driver', + 'verbose_name_plural': 'drivers', + }, + managers=[ + ('objects', django.contrib.auth.models.UserManager()), + ], + ), + migrations.CreateModel( + name='Manufacturer', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ('country', models.CharField(max_length=255)), + ], + ), + migrations.CreateModel( + name='Car', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('model', models.CharField(max_length=255)), + ('drivers', models.ManyToManyField(related_name='cars', to=settings.AUTH_USER_MODEL)), + ('manufacturer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='taxi.manufacturer')), + ], + ), + ] diff --git a/taxi/migrations/0002_alter_manufacturer_options_and_more.py b/taxi/migrations/0002_alter_manufacturer_options_and_more.py new file mode 100644 index 00000000..a056822c --- /dev/null +++ b/taxi/migrations/0002_alter_manufacturer_options_and_more.py @@ -0,0 +1,22 @@ +# Generated by Django 4.0.2 on 2022-04-12 06:44 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('taxi', '0001_initial'), + ] + + operations = [ + migrations.AlterModelOptions( + name='manufacturer', + options={'ordering': ['name']}, + ), + migrations.AlterField( + model_name='driver', + name='license_number', + field=models.CharField(max_length=255, unique=True), + ), + ] diff --git a/taxi/migrations/__init__.py b/taxi/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/taxi/models.py b/taxi/models.py new file mode 100644 index 00000000..679d3052 --- /dev/null +++ b/taxi/models.py @@ -0,0 +1,33 @@ +from django.db import models +from django.contrib.auth.models import AbstractUser + + +class Manufacturer(models.Model): + name = models.CharField(max_length=255) + country = models.CharField(max_length=255) + + class Meta: + ordering = ["name"] + + def __str__(self): + return f"{self.name} {self.country}" + + +class Driver(AbstractUser): + license_number = models.CharField(max_length=255, unique=True) + + class Meta: + verbose_name = "driver" + verbose_name_plural = "drivers" + + def __str__(self): + return f"{self.username} ({self.first_name} {self.last_name})" + + +class Car(models.Model): + model = models.CharField(max_length=255) + manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) + drivers = models.ManyToManyField(Driver, related_name="cars") + + def __str__(self): + return self.model diff --git a/taxi/tests.py b/taxi/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/taxi/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/taxi/urls.py b/taxi/urls.py new file mode 100644 index 00000000..035fa4e9 --- /dev/null +++ b/taxi/urls.py @@ -0,0 +1,14 @@ +from django.urls import path + +from .views import index, CarListView, CarDetailView, DriverListView, DriverDetailView, ManufacturerListView + +urlpatterns = [ + path("", index, name="index"), + path("manufacturers/", ManufacturerListView.as_view(), name="manufacturer_list"), + path("cars/", CarListView.as_view(), name="car_list"), + path("cars//", CarDetailView.as_view(), name="car_detail"), + path("drivers/", DriverListView.as_view(), name="driver_list"), + path("drivers//", DriverDetailView.as_view(), name="driver_detail") +] + +app_name = "taxi" diff --git a/taxi/views.py b/taxi/views.py new file mode 100644 index 00000000..d798b491 --- /dev/null +++ b/taxi/views.py @@ -0,0 +1,48 @@ +from django.shortcuts import render +from django.views import generic + +from .models import Driver, Car, Manufacturer + + + +def index(request): + """View function for the home page of the site.""" + + num_drivers = Driver.objects.count() + num_cars = Car.objects.count() + num_manufacturers = Manufacturer.objects.count() + + context = { + "num_drivers": num_drivers, + "num_cars": num_cars, + "num_manufacturers": num_manufacturers, + } + + return render(request, "taxi/index.html", context=context) + + +class ManufacturerListView(generic.ListView): + model = Manufacturer + context_object_name = "manufacturer_list" + template_name = "taxi/manufacturer_list.html" + paginate_by = 2 + + +class CarListView(generic.ListView): + model = Car + paginate_by = 2 + queryset = Car.objects.all().select_related("manufacturer") + + +class CarDetailView(generic.DetailView): + model = Car + + +class DriverListView(generic.ListView): + model = Driver + paginate_by = 2 + + +class DriverDetailView(generic.DetailView): + model = Driver + queryset = Driver.objects.all().prefetch_related("cars__manufacturer") \ No newline at end of file diff --git a/taxi_service/__init__.py b/taxi_service/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/taxi_service/asgi.py b/taxi_service/asgi.py new file mode 100644 index 00000000..b503e3ee --- /dev/null +++ b/taxi_service/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for taxi_service 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/4.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "taxi_service.settings") + +application = get_asgi_application() diff --git a/taxi_service/settings.py b/taxi_service/settings.py new file mode 100644 index 00000000..4b208e80 --- /dev/null +++ b/taxi_service/settings.py @@ -0,0 +1,129 @@ +""" +Django settings for taxi_service project. + +Generated by "django-admin startproject" using Django 4.0.2. + +For more information on this file, see +https://docs.djangoproject.com/en/4.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.0/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/4.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "django-insecure-8ovil3xu6=eaoqd#-#&ricv159p0pypoh5_lgm*)-dfcjqe=yc" + +# 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", + "taxi", +] + +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 = "taxi_service.urls" + +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [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 = "taxi_service.wsgi.application" + + +# Database +# https://docs.djangoproject.com/en/4.0/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.0/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", + }, +] + +AUTH_USER_MODEL = "taxi.Driver" + +# Internationalization +# https://docs.djangoproject.com/en/4.0/topics/i18n/ + +LANGUAGE_CODE = "en-us" + +TIME_ZONE = "Europe/Kiev" + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.0/howto/static-files/ + +STATIC_URL = "static/" + +STATICFILES_DIRS = (BASE_DIR / "static",) + +STATIC_ROOT = BASE_DIR / "staticfiles" + +# Default primary key field type +# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" diff --git a/taxi_service/urls.py b/taxi_service/urls.py new file mode 100644 index 00000000..8b94449f --- /dev/null +++ b/taxi_service/urls.py @@ -0,0 +1,25 @@ +"""taxi_service URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.0/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, include +from django.conf import settings +from django.conf.urls.static import static + + +urlpatterns = [ + path("admin/", admin.site.urls), + path("", include("taxi.urls", namespace="taxi")), +] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) diff --git a/taxi_service/wsgi.py b/taxi_service/wsgi.py new file mode 100644 index 00000000..f568b404 --- /dev/null +++ b/taxi_service/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for taxi_service 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/4.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "taxi_service.settings") + +application = get_wsgi_application() diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 00000000..03f76e0f --- /dev/null +++ b/templates/base.html @@ -0,0 +1,40 @@ + + + + + {% block title %}Taxi Service{% endblock %} + + + + + {% load static %} + + + + +
+
+
+ + {% block sidebar %} + {% include "includes/sidebar.html" %} + {% endblock %} + +
+
+ + {% block content %}{% endblock %} + + {% block pagination %} + {% include "includes/pagination.html" %} + {% endblock %} + +
+
+
+ + + diff --git a/templates/includes/pagination.html b/templates/includes/pagination.html new file mode 100644 index 00000000..118c2806 --- /dev/null +++ b/templates/includes/pagination.html @@ -0,0 +1,17 @@ +{% if is_paginated %} + +{% endif %} diff --git a/templates/includes/sidebar.html b/templates/includes/sidebar.html new file mode 100644 index 00000000..fbe0f8f2 --- /dev/null +++ b/templates/includes/sidebar.html @@ -0,0 +1,6 @@ + diff --git a/templates/taxi/car_detail.html b/templates/taxi/car_detail.html new file mode 100644 index 00000000..db6da00a --- /dev/null +++ b/templates/taxi/car_detail.html @@ -0,0 +1,12 @@ +{% extends "base.html" %} + +{% block content %} +

Manufacturer: ({{ car.manufacturer.name }}, {{ car.manufacturer.country }})

+

Drivers

+
+ +{% endblock %} diff --git a/templates/taxi/car_list.html b/templates/taxi/car_list.html new file mode 100644 index 00000000..c8539850 --- /dev/null +++ b/templates/taxi/car_list.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} + +{% block content %} +

Car list

+ {% if car_list %} + + {% else %} +

There are no cars in taxi

+ {% endif %} +{% endblock %} diff --git a/templates/taxi/driver_detail.html b/templates/taxi/driver_detail.html new file mode 100644 index 00000000..37b766d0 --- /dev/null +++ b/templates/taxi/driver_detail.html @@ -0,0 +1,18 @@ +{% extends "base.html" %} + +{% block content %} +

+ {{ driver.first_name }} {{ driver.last_name }}. + License number: {{ driver.license_number }} +

+ {% for car in driver.cars.all %} +
+

Id:{{ car.id }} + Car model: {{ car.model }} +

+ + {% empty %} +

No cars!

+ {% endfor %} + +{% endblock %} diff --git a/templates/taxi/driver_list.html b/templates/taxi/driver_list.html new file mode 100644 index 00000000..d5812999 --- /dev/null +++ b/templates/taxi/driver_list.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} + +{% block content %} +

Driver list

+ {% if driver_list %} + + {% else %} +

There are no drivers in taxi

+ {% endif %} +{% endblock %} diff --git a/templates/taxi/index.html b/templates/taxi/index.html new file mode 100644 index 00000000..13c59aa8 --- /dev/null +++ b/templates/taxi/index.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% block content %} +

Taxi Service Home

+

Welcome to Best Taxi Ever!

+

Dynamic content

+

The Taxi service has the following record counts:

+ +{% endblock %} diff --git a/templates/taxi/manufacturer_list.html b/templates/taxi/manufacturer_list.html new file mode 100644 index 00000000..f231d11d --- /dev/null +++ b/templates/taxi/manufacturer_list.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% block content %} +

Manufacturer list

+ + {% if manufacturer_list %} + + {% endif %} +{% endblock %} \ No newline at end of file diff --git a/tests/test_main.py b/tests/test_main.py deleted file mode 100644 index 6d8b3235..00000000 --- a/tests/test_main.py +++ /dev/null @@ -1,6 +0,0 @@ -# TODO: add tests -from app.main import hello_world - - -def test_hello_world(): - assert hello_world() == "Hello, world!"