-
Notifications
You must be signed in to change notification settings - Fork 0
дз №14, задача 2 #175
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AlenaStupina
wants to merge
2
commits into
main
Choose a base branch
from
AlenaStupina
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
дз №14, задача 2 #175
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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',) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
|
|
||
|
|
||
|
|
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| {% 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 %} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'), | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 not shown.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
у меня тут код частично дублируется из шаблона films.html. Как расширить шаблон films.html?
There was a problem hiding this comment.
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