from django.shortcuts import redirect
from django.views.generic import DetailView, ListView
from django.views.generic.base import View
from .forms import ReviewForm
from .models import Movie, Actor, Ganer
class GanerYear:
"""Жанры и года выхода фильмов"""
def get_ganres(self):
return Ganer.objects.all()
def get_years(self):
return Movie.objects.filter(draft=False).values('year')
class MoviesListView(GanerYear, ListView):
"""Вывод все фильмов на главнаю"""
model = Movie
template_name = 'movies/movie_list.html.twig'
context_object_name = 'movie_list'
allow_empty = False
queryset = Movie.objects.filter(draft=False)
class MovieDetailView(GanerYear, DetailView):
"""Вывод детальной информации о фильме"""
model = Movie
template_name = 'movies/movie_detail.html.twig'
context_object_name = 'movie'
allow_empty = False
class AddReview(View):
"""Отзывы"""
def post(self, request, pk):
form = ReviewForm(request.POST)
movie = Movie.objects.get(id=pk)
if form.is_valid():
form = form.save(commit=False)
if request.POST.get('parent', None):
form.parent_id = int(request.POST.get('parent'))
form.movie = movie
form.save()
return redirect(movie.get_absolute_url())
class ActorDetailView(GanerYear, DetailView):
"""Вывод информации о актере"""
model = Actor
template_name = 'movies/actor.html.twig'
context_object_name = 'actor'
allow_empty = False
class FilterMoviesView(GanerYear, ListView):
"""Фильтр фильмов"""
def get_queryset(self):
queryset = Movie.objects.filter(year__in=self.request.GET.getlist("year"))
return queryset
from django.db import models
from datetime import date
from django.urls import reverse
class Category(models.Model):
"""Категории"""
name = models.CharField('Категория', max_length=160)
descriptions = models.TextField('Описание')
slug = models.SlugField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('index', kwargs={'slug': self.slug})
def __str__(self):
return self.name
class Meta:
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
class Actor(models.Model):
"""Актёры и режиссеры"""
name = models.CharField('Имя', max_length=100)
birthday = models.DateField('Дата рождения', null=True)
descriptions = models.TextField('Описание')
image = models.ImageField('Изображение', upload_to='actor/')
slug = models.SlugField(max_length=100, unique=True)
def calculate_age(self):
"""Расчёт возроста"""
dob = self.birthday
today = date.today()
if dob:
m = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
k = m % 10
if (m > 9) and (m < 20) or (m > 110) or (k > 4) or (k == 0):
return f'{m} лет'
elif k == 1:
return f'{m} год'
else:
return f'{m} года'
calculate_age.short_description = 'Возрост'
def get_absolute_url(self):
return reverse('actor_detail', kwargs={'slug': self.slug})
def __str__(self):
return self.name
class Meta:
verbose_name = 'Актёры и режиссеры'
verbose_name_plural = 'Актёры и режиссеры'
class Ganer(models.Model):
"""Жанры"""
name = models.CharField('Имя', max_length=100)
descriptions = models.TextField('Описание')
slug = models.SlugField(max_length=160, unique=True)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Жанр'
verbose_name_plural = 'Жанры'
class Movie(models.Model):
"""Фильмы"""
title = models.CharField('Название', max_length=100)
descriptions = models.TextField('Описание')
image = models.ImageField('Постер', upload_to='movies/')
year = models.PositiveSmallIntegerField('Год производства', default=2020)
country = models.CharField('Страна', max_length=30)
directors = models.ManyToManyField(Actor, verbose_name='Режиссёр', related_name='film_director')
actors = models.ManyToManyField(Actor, verbose_name='Актёр', related_name='film_actor')
genres = models.ManyToManyField(Ganer, verbose_name='Жанр')
category = models.ForeignKey(Category, verbose_name='Категория', on_delete=models.SET_NULL, null=True)
world_premiere = models.DateField('Примьера в мире', default=date.today)
budget = models.PositiveIntegerField('Бюджет', default=0, help_text='указывать сумму в доларах')
fees_in_usa = models.PositiveIntegerField('Сборы в США', default=0, help_text='указывать сумму в доларах')
fees_in_world = models.PositiveIntegerField('Сборы в Мире', default=0, help_text='указывать сумму в доларах')
draft = models.BooleanField('Черновик', default=False)
slug = models.SlugField(max_length=130, unique=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('movie_detail', kwargs={'slug': self.slug})
def get_reviews(self):
return self.reviews_set.filter(parent__isnull=True)
class Meta:
verbose_name = 'Фильм'
verbose_name_plural = 'Фильмы'
class MovieShots(models.Model):
"""Кадры из фильма"""
title = models.CharField('Заголовок', max_length=100)
description = models.TextField('Описание')
image = models.ImageField('Изображение', upload_to='movie_shots/')
movie = models.ForeignKey(Movie, verbose_name='Фильм', on_delete=models.CASCADE)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Кадр из фильма'
verbose_name_plural = 'Кадры из фильма'
class RatingStar(models.Model):
"""Звезда рейтенга"""
value = models.PositiveSmallIntegerField('Значение', default=0)
def __str__(self):
return self.value
class Meta:
verbose_name = 'Звезда рейтенга'
verbose_name_plural = 'Звезды рейтенга'
class Rating(models.Model):
"""Рейтинг"""
ip = models.CharField('IP адрес', max_length=15)
star = models.ForeignKey(RatingStar, on_delete=models.CASCADE, verbose_name='Звезда')
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, verbose_name='Фильм')
def __str__(self):
return f'{self.star} - {self.movie}'
class Meta:
verbose_name = 'Рейтинг'
verbose_name_plural = 'Рейтинги'
class Reviews(models.Model):
"""Отзовы"""
email = models.EmailField()
name = models.CharField('Имя', max_length=100)
text = models.TextField('Сообщение', max_length=5000)
parent = models.ForeignKey('self', verbose_name='Родитель', on_delete=models.CASCADE, blank=True, null=True)
movie = models.ForeignKey(Movie, verbose_name='Фильм', on_delete=models.CASCADE)
def __str__(self):
return f'{self.name} - {self.movie}'
class Meta:
verbose_name = 'Отзыв'
verbose_name_plural = 'Отзывы'
from django.urls import path
from . import views
urlpatterns = [
path('', views.MoviesListView.as_view(), name='index'),
path('filter/', views.FilterMoviesView.as_view(), name='filter'),
path('movies/<str:slug>', views.MovieDetailView.as_view(), name='movie_detail'),
path('review/<int:pk>', views.AddReview.as_view(), name='add_review'),
path('actor/<str:slug>', views.ActorDetailView.as_view(), name='actor_detail'),
]
<form action="{% url 'filter' %}" method="get">
<div class="left-side">
<h3 class="sear-head editContent">Год</h3>
<ul class="w3layouts-box-list">
{% for movie in view.get_years %}
<li class="editContent">
<input type="checkbox" class="checked" name="year" value="{{ movie.year }}">
<span class="span editContent">{{ movie.year }}</span>
</li>
{% endfor %}
</ul>
</div>
<button type="submit">Найти</button>
</form>