This commit is contained in:
2025-11-27 16:02:44 +01:00
parent c3c0679c49
commit 9a01115b5a
23 changed files with 617 additions and 9 deletions

79
.gitignore vendored
View File

@@ -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/

View File

@@ -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

0
app/__init__.py Normal file
View File

0
app/app/__init__.py Normal file
View File

16
app/app/asgi.py Normal file
View File

@@ -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()

123
app/app/settings.py Normal file
View File

@@ -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'

22
app/app/urls.py Normal file
View File

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

16
app/app/wsgi.py Normal file
View File

@@ -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()

16
app/asgi.py Normal file
View File

@@ -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()

22
app/manage.py Executable file
View File

@@ -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()

123
app/settings.py Normal file
View File

@@ -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'

13
app/urls.py Normal file
View File

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

16
app/wsgi.py Normal file
View File

@@ -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()

0
books/__init__.py Normal file
View File

30
books/admin.py Normal file
View File

@@ -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)

6
books/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class BooksConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'books'

View File

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

View File

24
books/models.py Normal file
View File

@@ -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"

3
books/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
books/views.py Normal file
View File

@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

22
manage.py Executable file
View File

@@ -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()

3
requirements.txt Normal file
View File

@@ -0,0 +1,3 @@
asgiref==3.8.1
Django==5.2
sqlparse==0.5.3