diff --git a/.gitignore b/.gitignore index 36b13f1..8df9338 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,75 @@ +# Python +__pycache__/ +*.py[cod] +*.pyo +*.pyd +*.so +*.egg-info/ +*.log +*.pot +*.mo +*.pickle +*.pyc +.Python +.env +.venv +venv/ +env/ +ENV/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +pip-wheel-metadata/ +wheels/ +*.manifest +*.spec + +# Virtual Environment +venv/ +env/ +.venv/ +ENV/ + +# IDE / Editors +.vscode/ +.idea/ +*.sublime-project +*.sublime-workspace +*.swp +*.tmp + +# Testing +htmlcov/ +.coverage +.tox/ +.nox/ +.pytest_cache/ +coverage.xml +test_results/ +junitxml.xml + +# Caches +.cache/ +sass-cache/ +*.cache + +# OS-specific files +.DS_Store +Thumbs.db + +# PyCharm specific +*.iml +.vscode/ +.idea/ + + + + + + + # ---> Python # Byte-compiled / optimized / DLL files __pycache__/ @@ -161,13 +233,6 @@ dmypy.json # Cython debug symbols cython_debug/ -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ - # Ruff stuff: .ruff_cache/ diff --git a/README.md b/README.md index aa2235f..d92c964 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,57 @@ -# django_przyklad_generic_admin +# Przykładowa aplikacja w Django + +Przykład projektu Django z widokami generycznymi. +Logowanie: admin, hasło: ZAQ!2wsx + +# Wymagania + +Zainstalowany Python 3.10+ + +Sprawdź: python --version + +albo + +python3 --version + +Jeśli masz oba, na Linux/Mac zwykle używasz python3, na Windows – python. + +Wymagany program GIT + +# Instalacja + +1. Sklonuj repozytorium na dysk + git clone https://git.smartwmt.pl/admin/django_przyklad_generic_admin.git +2. Otwórz folder projektu np. w Visual Studio Code +3. Terminal -> Nowy terminal +4. Utwórz i włącz wirtualne środowisko python -m vevn venv +5. Aktywuj środowisko wirtualne: + + Windows: venv\Scripts\activate + + Linux / macOS: source venv/bin/activate +6. Po aktywacji w konsoli powinna pojawić się nazwa środowiska, np. (venv). +7. Zainstaluj zależności z pliku requirements.txt + + pip install -r requirements.txt +8. Uruchom serwer: + + python manage.py runserver + +## Jeśli usuniesz bazę i chcesz utworzyć nową i superużytkownika + +1. Utwórz bazę (migracje) + + python manage.py migrate +2. Utwórz konto administratora + + python manage.py createsuperuser + +3. Uruchom serwer developerski + + python manage.py runserver + +Domyślnie aplikacja działa pod adresem: + +http://127.0.0.1:8000/ (to samo co http://localhost:8000/) + -Przykład projektu Django z widokami generycznymi. Logowanie: admin, hasło: 12345678 \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/app/__init__.py b/app/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/app/asgi.py b/app/app/asgi.py new file mode 100644 index 0000000..b6bc9f6 --- /dev/null +++ b/app/app/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for app 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/5.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') + +application = get_asgi_application() diff --git a/app/app/settings.py b/app/app/settings.py new file mode 100644 index 0000000..82c6f72 --- /dev/null +++ b/app/app/settings.py @@ -0,0 +1,123 @@ +""" +Django settings for app project. + +Generated by 'django-admin startproject' using Django 5.2. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.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/5.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-ykiu*q%$5via+9q+q0(@mwl9@m5-%tz14vh#%63q%up@s#9$e_' + +# 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', + 'books', +] + +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 = 'app.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'app.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.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/5.2/topics/i18n/ + +LANGUAGE_CODE = 'pl-pl' + +TIME_ZONE = 'Europe/Warsaw' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/app/app/urls.py b/app/app/urls.py new file mode 100644 index 0000000..93599f7 --- /dev/null +++ b/app/app/urls.py @@ -0,0 +1,22 @@ +""" +URL configuration for app project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.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 + +urlpatterns = [ + path('admin/', admin.site.urls), +] diff --git a/app/app/wsgi.py b/app/app/wsgi.py new file mode 100644 index 0000000..121dd78 --- /dev/null +++ b/app/app/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for app 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/5.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') + +application = get_wsgi_application() diff --git a/app/asgi.py b/app/asgi.py new file mode 100644 index 0000000..b6bc9f6 --- /dev/null +++ b/app/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for app 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/5.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') + +application = get_asgi_application() diff --git a/app/manage.py b/app/manage.py new file mode 100755 index 0000000..4931389 --- /dev/null +++ b/app/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', 'app.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/app/settings.py b/app/settings.py new file mode 100644 index 0000000..5f7cf19 --- /dev/null +++ b/app/settings.py @@ -0,0 +1,123 @@ +""" +Django settings for app project. + +Generated by 'django-admin startproject' using Django 5.2. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.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/5.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-!!e%ygr3)s25q!jm51av2**s^tj7fl3pfbw(9q3af(@dq*fwx3' + +# 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', + 'books', +] + +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 = 'app.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'app.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.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/5.2/topics/i18n/ + +LANGUAGE_CODE = 'pl-pl' + +TIME_ZONE = 'Europe/Warsaw' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/app/urls.py b/app/urls.py new file mode 100644 index 0000000..4d6d8e7 --- /dev/null +++ b/app/urls.py @@ -0,0 +1,13 @@ +from django.contrib import admin +from django.urls import path +from django.shortcuts import redirect + +urlpatterns = [ + path('admin/', admin.site.urls), + + # /books -> /admin/ + path('books/', lambda request: redirect('/admin/')), + + # / -> /admin/ + path('', lambda request: redirect('/admin/')), +] \ No newline at end of file diff --git a/app/wsgi.py b/app/wsgi.py new file mode 100644 index 0000000..121dd78 --- /dev/null +++ b/app/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for app 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/5.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') + +application = get_wsgi_application() diff --git a/books/__init__.py b/books/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/books/admin.py b/books/admin.py new file mode 100644 index 0000000..3295f78 --- /dev/null +++ b/books/admin.py @@ -0,0 +1,30 @@ +from django.contrib import admin + +# Register your models here. +from .models import Book, Author + +admin.site.site_header = "Moje Centrum Zarządzania" # Nagłówek na górze strony admina +admin.site.site_title = "Panel admina - Moja Aplikacja" # Tytuł strony (np. zakładki przeglądarki) +admin.site.index_title = "Witamy w panelu administracyjnym" # Nagłówek na stronie głównej po zalogowaniu + +class BookAdmin(admin.ModelAdmin): + list_display = ('title', 'author') + search_fields = ('title', 'author__name') + list_filter = ('author',) + ordering = ['title'] + fields = ['title', 'author'] + readonly_fields = ('id',) + +#admin.site.register(Book) +#admin.site.register(Author) + +admin.site.register(Book, BookAdmin) + +class BookInline(admin.TabularInline): + model = Book + extra = 1 + +class AuthorAdmin(admin.ModelAdmin): + inlines = [BookInline] + +admin.site.register(Author, AuthorAdmin) \ No newline at end of file diff --git a/books/apps.py b/books/apps.py new file mode 100644 index 0000000..a53388c --- /dev/null +++ b/books/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class BooksConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'books' diff --git a/books/migrations/0001_initial.py b/books/migrations/0001_initial.py new file mode 100644 index 0000000..3eeb5d6 --- /dev/null +++ b/books/migrations/0001_initial.py @@ -0,0 +1,31 @@ +# Generated by Django 5.2 on 2025-04-07 15:44 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Author', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=100)), + ], + ), + migrations.CreateModel( + name='Book', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=200)), + ('active', models.BooleanField(default=True)), + ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='books.author')), + ], + ), + ] diff --git a/books/migrations/__init__.py b/books/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/books/models.py b/books/models.py new file mode 100644 index 0000000..277edf3 --- /dev/null +++ b/books/models.py @@ -0,0 +1,24 @@ +from django.db import models + +# Create your models here. +class Author(models.Model): + name = models.CharField(max_length=100, verbose_name="Imię i nazwisko") + + def __str__(self): + return self.name + + class Meta: + verbose_name = "Autor" + verbose_name_plural = "Autorzy" + +class Book(models.Model): + title = models.CharField(max_length=200, verbose_name="Tytuł") + active = models.BooleanField(default=True, verbose_name="Aktywny") + author = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name="Autor") # (PROTECT, SET_NULL, RESTRICT). + + def __str__(self): + return self.title + + class Meta: + verbose_name = "Książka" + verbose_name_plural = "Książki" \ No newline at end of file diff --git a/books/tests.py b/books/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/books/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/books/views.py b/books/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/books/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..4931389 --- /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', 'app.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 new file mode 100644 index 0000000..4aea2e2 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +asgiref==3.8.1 +Django==5.2 +sqlparse==0.5.3