цифровая платформа — основная тема материала.
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#-(8tausqwbp$^+87g=e8*vkk^qxs*3c4j!1@q4sl8tgox-w-@'
# 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',
'learnbook.apps.LearnbookConfig',
]
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 = 'LS_Django.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 = 'LS_Django.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'learn_sys_dj2',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'mysql_ls',
'PORT': '3306'
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/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.0/howto/static-files/
STATIC_URL = '/static/'
# Redirect to home URL after login (Default redirects to /accounts/profile/)
LOGIN_REDIRECT_URL = '/'
# получение ссылки для сброса пароля в консоль
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
LS_Django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.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
# Используйте include() чтобы добавлять URL из каталога приложения
from django.urls import include
from django.urls import path
# Добавьте URL соотношения, чтобы перенаправить запросы с корневового URL, на URL приложения
from django.views.generic import RedirectView
# Используйте static() чтобы добавить соотношения для статических файлов
# Только на период разработки
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
]
urlpatterns += [
path('learnbook/', include('learnbook.urls')),
]
urlpatterns += [
path('', RedirectView.as_view(url='/learnbook/', permanent=True)),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# Add Django site authentication urls (for login, logout, password management)
urlpatterns += [
path('accounts/', include('django.contrib.auth.urls')),
]
from django.db import models
from django.urls import reverse # Used to generate URLs by reversing the URL patterns
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=200, help_text="Enter a book category (e.g. Science Fiction, Programming etc.)")
def __str__(self):
"""
String for representing the Model object (in Admin site etc.)
"""
return self.name
class Learnbook(models.Model):
title = models.CharField(max_length=200)
tutor = models.ForeignKey('Tutor', on_delete=models.SET_NULL, null=True)
# Foreign Key used because book can only have one author, but authors can have multiple books
# Author as a string rather than object because it hasn't been declared yet in the file.
summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book")
category = models.ManyToManyField(Category, help_text="Select a category for this book")
# ManyToManyField used because genre can contain many books. Books can cover many genres.
# Genre class has already been defined so we can specify the object above.
def __str__(self):
"""
String for representing the Model object.
"""
return self.title
def get_absolute_url(self):
"""
Returns the url to access a particular book instance.
"""
return reverse('learnbook-detail', args=[str(self.id)])
def display_category(self):
"""
Creates a string for the Tutor. This is required to display tutor in Admin.
"""
return ', '.join([category.name for category in self.category.all()[:3]])
for representing the Model object.
«»»
return self.title
def get_absolute_url(self):
«»»
Returns the url to access a particular book instance.
«»»
return reverse(‘learnbook-detail’, args=[str(self.id)])
def display_category(self):
«»»
Creates a string for the Tutor. This is required to display tutor in Admin.
«»»
return ‘, ‘.join([category.name for category in self.category.all()[:3]])
display_category.short_description = ‘Category’
class Tutor(models.Model):
«»»
Model representing an author.
«»»
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
description = models.TextField(max_length=1000, help_text=»Info about Tutor / Информация о преподавателе»)
def get_absolute_url(self):
«»»
Returns the url to access a particular author instance.
«»»
return reverse(‘tutor-detail’, args=[str(self.id)])
def __str__(self):
«»»
String for representing the Model object.
«»»
# return ‘%s, %s’ % (self.last_name, self.first_name)
return ‘%s %s’ % (self.last_name, self.first_name)
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns = [
path(», views.index, name=’index’),
url(r’^learnbooks/$’, views.LearnbookListView.as_view(), name=’learnbooks’),
url(r’^learnbook/(?P<pk>d+)$’, views.LearnbookDetailView.as_view(), name=’learnbook-detail’),
url(r’^tutors/$’, views.TutorListView.as_view(), name=’tutors’),
url(r’^tutor/(?P<pk>d+)$’, views.TutorDetailView.as_view(), name=’tutor-detail’),
]
STATIC_URL = ‘/static/’
from django.contrib import admin
# Register your models here.
from .models import Tutor, Category, Learnbook
# admin.site.register(Tutor)
class LearnbookInstanceInline(admin.TabularInline):
model = Learnbook
extra = 0
# Define the admin class
class TutorAdmin(admin.ModelAdmin):
list_display = (‘first_name’, ‘last_name’, ‘description’)
# fields = [‘first_name’, ‘last_name’, (‘description’)]
# fieldsets = (
# (‘Description’, {
# ‘fields’: (‘description’, ‘last_name’)
# }),
# )
inlines = [LearnbookInstanceInline]
# Register the admin class with the associated model
admin.site.register(Tutor, TutorAdmin)
# admin.site.register(Category)
# Register the Admin class for Category using the decorator
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
pass
# list_display = (‘id’, ‘name’)
# admin.site.register(Learnbook)
# Register the Admin class for Category using the decorator
@admin.register(Learnbook)
class LearnbookAdmin(admin.ModelAdmin):
list_display = (‘title’, ‘summary’, ‘display_category’)
list_filter = (‘summary’, ‘tutor_id’)
2
