Первая версия

This commit is contained in:
2025-01-16 13:36:07 +03:00
commit 8d1b2c357e
22 changed files with 579 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
venv

36
bookify/.gitignore vendored Normal file
View File

@@ -0,0 +1,36 @@
.idea
idea
.DS_Store
*.egg-info/
.installed.cfg
*.egg
dist
db.sqlite3
venv
prod_settings.py
local_settings.py
__pycache__/
*/__pycache__/
*.py[cod]
.pyc
*.pyc
!*media
media/*
log/debug.log
build
doc
home.rst
make.bat
Makefile
doc-dev
books/migrations

View File

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

@@ -0,0 +1,16 @@
"""
ASGI config for bookify 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.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookify.settings')
application = get_asgi_application()

124
bookify/bookify/settings.py Normal file
View File

@@ -0,0 +1,124 @@
"""
Django settings for bookify project.
Generated by 'django-admin startproject' using Django 5.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-c1_r=$!h*n-@r1u-r#9x*xsgs7$a*2cnr7!c8=+irf!*4@g$$2"
# 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 = "bookify.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"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 = "bookify.wsgi.application"
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/5.1/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.1/topics/i18n/
LANGUAGE_CODE = "ru"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

7
bookify/bookify/urls.py Normal file
View File

@@ -0,0 +1,7 @@
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("books.urls", namespace="books")),
]

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

@@ -0,0 +1,16 @@
"""
WSGI config for bookify 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.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookify.settings')
application = get_wsgi_application()

View File

21
bookify/books/admin.py Normal file
View File

@@ -0,0 +1,21 @@
from django.contrib import admin
from .models import Book, Genre, Review
@admin.register(Genre)
class GenreAdmin(admin.ModelAdmin):
list_display = ("id", "name")
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ("id", "title", "author")
search_fields = ("title", "author")
list_filter = ("genres",)
@admin.register(Review)
class ReviewAdmin(admin.ModelAdmin):
list_display = ("id", "book", "user_name", "rating", "created_at")
list_filter = ("book", "rating")

6
bookify/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'

27
bookify/books/forms.py Normal file
View File

@@ -0,0 +1,27 @@
from django import forms
from .models import Book, Genre, Review
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ["title", "author", "description", "cover_image", "genres"]
widgets = {
"genres": forms.CheckboxSelectMultiple(),
}
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ["user_name", "rating", "text"]
widgets = {
"rating": forms.NumberInput(attrs={"min": 1, "max": 5}),
}
class GenreForm(forms.ModelForm):
class Meta:
model = Genre
fields = ["name"]

32
bookify/books/models.py Normal file
View File

@@ -0,0 +1,32 @@
from django.contrib.auth.models import User
from django.db import models
class Genre(models.Model):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
description = models.TextField()
genres = models.ManyToManyField(Genre, related_name="books")
cover_image = models.URLField(blank=True, null=True) # Можно хранить URL обложки
def __str__(self):
return self.title
class Review(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="reviews")
# Если планируется использовать Django-аутентификацию, можно связать с User
user_name = models.CharField(max_length=100)
rating = models.PositiveIntegerField(default=1) # от 1 до 5, например
text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Отзыв от {self.user_name} на книгу «{self.book}»"

View File

@@ -0,0 +1,73 @@
/* static/css/style.css */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header, footer {
background-color: #eee;
padding: 15px;
}
header h1, header nav {
display: inline-block;
vertical-align: middle;
margin: 0;
}
header h1 a {
text-decoration: none;
color: #333;
}
header nav {
float: right;
}
header nav a {
margin-left: 10px;
text-decoration: none;
color: #333;
}
main {
padding: 20px;
}
.book-list {
display: flex;
flex-direction: column;
gap: 1rem;
}
.book-item {
padding: 10px;
border-bottom: 1px solid #ccc;
}
.book-item h3 {
margin: 5px 0;
}
.btn-delete {
color: red;
text-decoration: none;
}
.reviews-section {
margin-top: 20px;
}
.review {
margin-bottom: 10px;
}
.add-review {
margin-top: 20px;
}
footer p {
text-align: center;
margin: 0;
}

View File

@@ -0,0 +1,10 @@
<!-- books/templates/books/add_book.html -->
{% extends 'books/base.html' %}
{% block content %}
<h2>Добавить книгу</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Сохранить</button>
</form>
{% endblock %}

View File

@@ -0,0 +1,26 @@
<!-- books/templates/books/base.html -->
{% load static %}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Приложение для книг</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<header>
<h1><a href="{% url 'books:book_list' %}">Bookify</a></h1>
<nav>
<a href="{% url 'books:add_book' %}">Добавить книгу</a>
</nav>
</header>
<main>
{% block content %}{% endblock %}
</main>
<footer>
<p>Bookify © 2025</p>
</footer>
</body>
</html>

View File

@@ -0,0 +1,44 @@
<!-- books/templates/books/book_detail.html -->
{% extends 'books/base.html' %}
{% block content %}
<div class="book-detail">
<h2>{{ book.title }}</h2>
<p><strong>Автор:</strong> {{ book.author }}</p>
<p><strong>Описание:</strong> {{ book.description }}</p>
{% if book.cover_image %}
<img src="{{ book.cover_image }}" alt="Обложка книги" style="max-width:200px;">
{% endif %}
<p><strong>Жанры:</strong>
{% for g in book.genres.all %}
<a href="{% url 'books:genre_recommendations' g.name %}">{{ g.name }}</a>{% if not forloop.last %}, {% endif %}
{% endfor %}
</p>
<p>
<a class="btn-delete" href="{% url 'books:delete_book' book.pk %}">Удалить книгу</a>
</p>
</div>
<div class="reviews-section">
<h3>Отзывы</h3>
{% for review in reviews %}
<div class="review">
<p><strong>{{ review.user_name }}</strong> ({{ review.rating }}/5)</p>
<p>{{ review.text }}</p>
<hr>
</div>
{% empty %}
<p>Пока нет отзывов.</p>
{% endfor %}
</div>
<div class="add-review">
<h3>Добавить отзыв</h3>
<form method="POST" action="{% url 'books:add_review' book.pk %}">
{% csrf_token %}
{{ review_form.as_p }}
<button type="submit">Отправить</button>
</form>
</div>
{% endblock %}

View File

@@ -0,0 +1,21 @@
<!-- books/templates/books/book_list.html -->
{% extends 'books/base.html' %}
{% load static %}
{% block content %}
<h2>Список книг</h2>
<div class="book-list">
{% for book in books %}
<div class="book-item">
<h3><a href="{% url 'books:book_detail' book.pk %}">{{ book.title }}</a></h3>
<p>Автор: {{ book.author }}</p>
{% if book.genres.all %}
<p>Жанры:
{% for g in book.genres.all %}
<a href="{% url 'books:genre_recommendations' g.name %}">{{ g.name }}</a>{% if not forloop.last %}, {% endif %}
{% endfor %}
</p>
{% endif %}
</div>
{% endfor %}
</div>
{% endblock %}

View File

@@ -0,0 +1,13 @@
<!-- books/templates/books/genre_recommendations.html -->
{% extends 'books/base.html' %}
{% block content %}
<h2>Рекомендации по жанру "{{ genre.name }}"</h2>
<div class="book-list">
{% for book in books %}
<div class="book-item">
<h3><a href="{% url 'books:book_detail' book.pk %}">{{ book.title }}</a></h3>
<p>Автор: {{ book.author }}</p>
</div>
{% endfor %}
</div>
{% endblock %}

3
bookify/books/tests.py Normal file
View File

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

18
bookify/books/urls.py Normal file
View File

@@ -0,0 +1,18 @@
from django.urls import path
from . import views
app_name = "books"
urlpatterns = [
path("", views.book_list, name="book_list"),
path("book/<int:pk>/", views.book_detail, name="book_detail"),
path("book/add/", views.add_book, name="add_book"),
path("book/delete/<int:pk>/", views.delete_book, name="delete_book"),
path("book/<int:pk>/add_review/", views.add_review, name="add_review"),
path(
"genres/<str:genre_name>/",
views.genre_recommendations,
name="genre_recommendations",
),
]

63
bookify/books/views.py Normal file
View File

@@ -0,0 +1,63 @@
from django.shortcuts import get_object_or_404, redirect, render
from .forms import BookForm, ReviewForm
from .models import Book, Genre, Review
def book_list(request):
"""Главная страница со списком всех книг."""
books = Book.objects.all()
return render(request, "books/book_list.html", {"books": books})
def book_detail(request, pk):
"""Детальная страница книги."""
book = get_object_or_404(Book, pk=pk)
reviews = book.reviews.all()
review_form = ReviewForm()
return render(
request,
"books/book_detail.html",
{"book": book, "reviews": reviews, "review_form": review_form},
)
def add_book(request):
"""Добавление новой книги."""
if request.method == "POST":
form = BookForm(request.POST)
if form.is_valid():
form.save()
return redirect("books:book_list")
else:
form = BookForm()
return render(request, "books/add_book.html", {"form": form})
def delete_book(request, pk):
"""Удаление книги."""
book = get_object_or_404(Book, pk=pk)
book.delete()
return redirect("books:book_list")
def add_review(request, pk):
"""Добавление отзыва к книге."""
book = get_object_or_404(Book, pk=pk)
if request.method == "POST":
form = ReviewForm(request.POST)
if form.is_valid():
review = form.save(commit=False)
review.book = book
review.save()
return redirect("books:book_detail", pk=pk)
def genre_recommendations(request, genre_name):
"""Рекомендации книг по заданному жанру."""
genre = get_object_or_404(Genre, name=genre_name)
# Выберем все книги, которые относятся к данному жанру
books = genre.books.all()
return render(
request, "books/genre_recommendations.html", {"genre": genre, "books": books}
)

22
bookify/manage.py Normal 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', 'bookify.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()