Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Practice/Stupina/coolapp/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.contrib import admin

# Register your models here.

from django.contrib import admin
from .models import Film, Comments

admin.site.register(Film)
admin.site.register(Comments)
15 changes: 15 additions & 0 deletions Practice/Stupina/coolapp/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from django import forms
from .models import Film, Comments


class FilmForm(forms.ModelForm):
class Meta:
model = Film
fields = ('name', 'state', 'date_exist', 'desc', 'rate')
# поля pub_date и id заполняются сами


class CommentsForm(forms.ModelForm):
class Meta:
model = Comments
fields = ('comment',)
24 changes: 24 additions & 0 deletions Practice/Stupina/coolapp/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator

# Create your models here.
class Film(models.Model):
#атрибуты name, desc, pub_date, rate - столбцы
name = models.CharField(max_length=200)
# TextField() - тип поля
state = models.TextField(null=True)
date_exist = models.DateField(default='0')
desc = models.TextField()
# 'date published' - как поле будет выглядеть при выводе на экран в терминале
# auto_now_add=True - когда будет добавляться новая запись,
# это поле будет автоматически проставляться, исходя из текущего времени
pub_date = models.DateTimeField('date published', auto_now_add=True)
rate = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)], default=1)


class Comments(models.Model):
films_id = models.ForeignKey(Film, on_delete=models.CASCADE, null=True)
comment = models.TextField()



Binary file added Practice/Stupina/coolapp/static/favicon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 22 additions & 0 deletions Practice/Stupina/coolapp/templates/coolapp/base.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
{% load static %}

<html lang="en">
<head>
<link rel="stylesheet" href="{% static 'css/main.css' %}">
<link rel="icon" href="{% static 'favicon.png' %}" type="image/x-icon">

<meta charset="UTF-8">
<!-- заголовок -->
<title>About films</title>
</head>
<body>

<h3><a href="/">Site about films</a></h3>
<p><a href="/films">Фильмы</a></p>
<p><a href="/new">Создать новый фильм</a></p>
<hr>
{% block content %}
{% endblock %}
</body>
</html>
25 changes: 25 additions & 0 deletions Practice/Stupina/coolapp/templates/coolapp/film_id.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{% extends 'coolapp/base.html' %}
{% block content %}


<h2> {{ film.name }} </h2>
<p> Страна : - {{ film.state }} </p>
<p> Описание: {{ film.desc }} </p>
<p> Дата создания: {{ film.date_exist }} </p>
{% if film.pub_date %}
<p> Дата публикации отзыва: - {{ film.pub_date }} </p>
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

у меня тут код частично дублируется из шаблона films.html. Как расширить шаблон films.html?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сделать общий шаблон film.html для films.html и film_id.html, "наследующий" base.html.
А films.html и film_id.html "унаследовать" от film.html

{% else %}
<p> Дата публикации отзыва: - Unknown </p>
{% endif %}
<p> Оценка: {{ film.rate }} </p>
{% for com in comm %}
<p> Комментарии: {{com.comment }} </p>
{% endfor %}

<p><u>Оставить комментарий:</u></p>
<form method="POST">{% csrf_token %}
{{ com_form.as_p }}

<button type="submit">Save</button>
</form>
{% endblock content %}
18 changes: 18 additions & 0 deletions Practice/Stupina/coolapp/templates/coolapp/films.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{% extends 'coolapp/base.html' %}
{% block content %}

<!-- {процент .. процент} - язык шаблонов Django -->
{% for film in films %}

<h2><a href="/{{film.id}}">{{ film.name }} </a></h2>
<p><b> Описание</b>: {{ film.desc }} </p>
{% if film.pub_date %}
<p><b> Дата публикации</b> : - {{ film.pub_date }} </p>
{% else %}
<p><b> Дата публикации</b>: - Unknown </p>
{% endif %}
<p><b> Оценка</b> : {{ film.rate }} </p>
{% endfor %}


{% endblock content %}
12 changes: 12 additions & 0 deletions Practice/Stupina/coolapp/templates/coolapp/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!-- Обычно (в html-практике) основной код веб-страницы размещается как раз в теге <body>.
Но браузер поймет даже, если мы оставим в этом файле только свой код. -->

{% extends 'coolapp/base.html' %}
{% block content %}
<div align = center>
<h1>Hello everybody!</h1>
<h2><i>Вы находитесь на сайте "{{sitename}}"</i>.</h2>
<p>Здесь Вы можете найти информацию о фильмах, их краткое описание и рейтинг </p>
</div>

{% endblock content %}
16 changes: 16 additions & 0 deletions Practice/Stupina/coolapp/templates/coolapp/new.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{% extends 'coolapp/base.html' %}
{% block content %}



<h1>Добавление нового фильма</h1>
{% if flag %}
<form method="POST">{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
{% else %}
<p> Ошибка: У Вас нет прав для данной операции! </p>
{% endif %}

{% endblock content %}
7 changes: 7 additions & 0 deletions Practice/Stupina/coolapp/templates/coolapp/no_exit.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

{% extends 'coolapp/base.html' %}
{% block content %}

<h2>Error: Фильма с таким id на сайте еще нет!</h2>

{% endblock content %}
14 changes: 14 additions & 0 deletions Practice/Stupina/coolapp/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from django.urls import path
from . import views

# ---если сюда приходит код какой-то,мы при помощи шаблона urlpatterns перенаправляем этот код в views.index.
# name='index' - это псевдоним для получившегося url, чтоб удобней было обращаться к тому же ресурсу (функции)
# из кода в некоторых случаях.

urlpatterns = [
path('', views.index, name='index'),
path('films/', views.films, name='films'),
path('new/', views.new, name='new'),
# если в запросе число:
path('<int:film_id>/', views.new, name='new'),
]
46 changes: 46 additions & 0 deletions Practice/Stupina/coolapp/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from django.shortcuts import render, redirect
from .models import Film, Comments
from .forms import FilmForm, CommentsForm


def index(request):
return render(request, 'coolapp/index.html', {'sitename': 'О фильмах'})


def films(request):
return render(request, 'coolapp/films.html', {'films': Film.objects.all()})


def new(request, film_id=None):
if film_id:
film = Film.objects.get(id=film_id)
if request.method == "POST":
text = request.POST['comment']
c = Comments(films_id=film, comment=text)
c.save()
return redirect(f'/{film.id}', film=film)

else:
try:
comments = Comments.objects.filter(films_id=film_id)
return render(request, 'coolapp/film_id.html',
{'film': film, 'comm': comments, 'com_form': CommentsForm(instance=Comments())})
except Exception:
return render(request, 'coolapp/no_exit.html')

elif request.method == "POST":
form = FilmForm(request.POST)
print(form.is_valid())
if form.is_valid():
film = form.save()
return redirect(f'/{film.id}', film=film)
else:
if request.user.is_superuser:
film = Film()
flag = True
d = {'form': FilmForm(instance=film)}
else:
flag = False
d = {}
d = d | {'flag': flag}
return render(request, 'coolapp/new.html', d)
127 changes: 127 additions & 0 deletions Practice/Stupina/coolsite/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"""
Django settings for coolsite project.

Generated by 'django-admin startproject' using Django 4.2.4.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path
import os

# 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.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-#*q%rz8b35ad*mn4tqj!e%tinjn_sjyxef$fokj#e9b%64+50p'

# 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',
'coolapp'
]

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 = 'coolsite.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 = 'coolsite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/4.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/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Europe/Moscow'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')


# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
35 changes: 35 additions & 0 deletions Practice/Stupina/coolsite/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
URL configuration for coolsite project.

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.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.conf.urls import include
from django.urls import path
from django.contrib import admin

# --прописываем связь с coolapp.urls
# Когда мы обращаемся к серверу (127.0.0.1:8000) приходит запрос,
# сервер начинает анализировать, что дальше идет посде запроса : # к какому ресурсу/файлу/скрипту на сервере идет обращение.
# 127.0.0.1:8000 - пустой запрос
# Если запрос 127.0.0.1:8000/coolapp/ - попадая в главный файл URL, указанная часть URL (coolapp)
# будет сравниваться с каждым шаблоном из списка (coolapp/ - шаблон). Если шаблон совпал, анализируется дальше.
# include('coolapp.urls') - расширяет шаблон: path('coolapp/', views.index, name='index'),
# и вызывается coolapp.views.index---


urlpatterns = [
path('admin/', admin.site.urls),
path('coolapp/', include('coolapp.urls')),
path('', include('coolapp.urls')),
]
Binary file added Practice/Stupina/db.sqlite3
Binary file not shown.
Loading