Skip to content

Commit

Permalink
Add templates data_location, csrf_button, customized admin menu.
Browse files Browse the repository at this point in the history
  • Loading branch information
Wiz410 committed Jun 21, 2023
1 parent b7b170a commit 761915e
Show file tree
Hide file tree
Showing 19 changed files with 302 additions and 179 deletions.
65 changes: 62 additions & 3 deletions blogicum/blog/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,65 @@

from .models import Category, Location, Post

admin.site.register(Category)
admin.site.register(Location)
admin.site.register(Post)
OBJECT_PER_PAGE: int = 10


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
"""Управление тематическими категориями."""
list_display = [
'title',
'description',
'is_published'
]
list_editable = [
'description',
'is_published'
]
list_per_page = OBJECT_PER_PAGE
ordering = [
'title',
'description'
]


@admin.register(Location)
class LocationAdmin(admin.ModelAdmin):
"""Управление геогрофическими метками."""
list_display = [
'name',
'is_published'
]
list_editable = [
'is_published'
]
list_per_page = OBJECT_PER_PAGE
ordering = [
'name',
'created_at'
]


@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
"""Управление публикациями."""
list_display = [
'title',
'text',
'location',
'pub_date',
'category',
'is_published'
]
list_editable = [
'text',
'location',
'pub_date',
'category',
'is_published'
]
list_per_page = OBJECT_PER_PAGE
ordering = [
'-pub_date',
'title'
]
85 changes: 14 additions & 71 deletions blogicum/blog/mixins.py
Original file line number Diff line number Diff line change
@@ -1,66 +1,19 @@
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone
from django.shortcuts import get_object_or_404, redirect

from .models import Post, Comment
from .forms import PostForm, CommentForm

POST_PER_PAGE: int = 10

DATENOW = timezone.now()

User = get_user_model()


class PaginatorMixin:
"""
Вспомогательный класс.
Добовляет разделение списка постов на страницы.
"""
paginate_by = POST_PER_PAGE


class ProfileMixin:
"""
Вспомогательный класс.
Указывает модель User для класса.
"""
model = User


class PostMixin:
"""
Вспомогательный класс.
Указывает модель Post для класса.
"""
model = Post


class CommentMixin:
"""
Вспомогательный класс.
Указывает модель Comment для класса.
"""
model = Comment


class CommentDispacthMixin:
class URLProfileMixin:
"""
Вспомогательный класс.
Указывает форму CommentForm.
Шаблон comment.html.
И переопределяет dispatch, для получения и проверки автора комментария.
Переопределяет get_success_url, для переадресовки на страницу профиля.
"""
form_class = CommentForm
pk_url_kwarg = 'comment_id'
template_name = 'blog/comment.html'

def dispatch(self, request, *args, **kwargs):
posts = get_object_or_404(Comment, id=self.kwargs['comment_id'])
if request.user != posts.author:
return redirect('blog:post_detail', post_id=posts.pk)
return super().dispatch(request, *args, **kwargs)
def get_success_url(self):
return reverse(
'blog:profile',
kwargs={'username': self.request.user}
)


class PostDispatchMixin:
Expand All @@ -75,16 +28,6 @@ def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)


class PostFormMixin:
"""
Вспомогательный класс.
Указывает форму PostForm.
И шаблон create.html
"""
form_class = PostForm
template_name = 'blog/create.html'


class URLPostMixin:
"""
Вспомогательный класс.
Expand All @@ -97,13 +40,13 @@ def get_success_url(self):
)


class URLProfileMixin:
class CommentDispacthMixin:
"""
Вспомогательный класс.
Переопределяет get_success_url, для переадресовки на страницу профиля.
Переопределяет dispatch, для получения и проверки автора комментария.
"""
def get_success_url(self):
return reverse(
'blog:profile',
kwargs={'username': self.request.user}
)
def dispatch(self, request, *args, **kwargs):
posts = get_object_or_404(Comment, id=self.kwargs['comment_id'])
if request.user != posts.author:
return redirect('blog:post_detail', post_id=posts.pk)
return super().dispatch(request, *args, **kwargs)
2 changes: 2 additions & 0 deletions blogicum/blog/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ class Comment(BaseModel, BaseAuthorModel):

class Meta:
ordering = ['created_at', 'author']
verbose_name = 'коментарий'
verbose_name_plural = 'Комментарии'

def __str__(self):
return self.author
83 changes: 40 additions & 43 deletions blogicum/blog/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# from django.http import HttpResponse, HttpRequest
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count, Q
Expand All @@ -13,30 +12,25 @@
from django.shortcuts import get_object_or_404

from .mixins import (
PaginatorMixin,
ProfileMixin,
PostMixin,
CommentMixin,
CommentDispacthMixin,
PostDispatchMixin,
PostFormMixin,
URLPostMixin,
URLProfileMixin,
)
from .forms import CommentForm, UserForm
from .forms import CommentForm, UserForm, PostForm
from .models import Post, Category, Comment

POST_PER_PAGE: int = 10

DATENOW = timezone.now()

User = get_user_model()


class IndexListView(
PostMixin,
PaginatorMixin,
ListView
):
class IndexListView(ListView):
"""Главная страница."""
model = Post
paginate_by = POST_PER_PAGE
template_name = 'blog/index.html'

def get_queryset(self):
Expand All @@ -47,11 +41,9 @@ def get_queryset(self):
).order_by('-pub_date').annotate(comment_count=Count('comment'))


class PostDetailView(
PostMixin,
DetailView
):
class PostDetailView(DetailView):
"""Страница поста."""
model = Post
template_name = 'blog/detail.html'
pk_url_kwarg = 'post_id'

Expand All @@ -67,28 +59,30 @@ def get_context_data(self, **kwargs):


class CreatePostCreateView(
PostMixin,
PostFormMixin,
LoginRequiredMixin,
URLProfileMixin,
LoginRequiredMixin,
CreateView
):
"""Создание поста."""
model = Post
form_class = PostForm
template_name = 'blog/create.html'

def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)


class EditPostUpdateView(
PostMixin,
PostFormMixin,
PostDispatchMixin,
LoginRequiredMixin,
URLPostMixin,
LoginRequiredMixin,
UpdateView
):
"""Редактирование поста."""
model = Post
form_class = PostForm
template_name = 'blog/create.html'
pk_url_kwarg = 'post_id'

def form_valid(self, form):
Expand All @@ -98,23 +92,22 @@ def form_valid(self, form):


class DeletePostDeleteView(
PostMixin,
PostFormMixin,
PostDispatchMixin,
LoginRequiredMixin,
URLProfileMixin,
LoginRequiredMixin,
DeleteView
):
"""Удаление поста."""
model = Post
form_class = PostForm
template_name = 'blog/create.html'
pk_url_kwarg = 'post_id'


class CategoryPostsListView(
PostMixin,
PaginatorMixin,
ListView
):
class CategoryPostsListView(ListView):
"""Страница с категориями."""
model = Post
paginate_by = POST_PER_PAGE
template_name = 'blog/category.html'
slug_url_kwarg = 'category_slug'

Expand All @@ -138,12 +131,10 @@ def get_queryset(self):
).order_by('-pub_date').annotate(comment_count=Count('comment'))


class ProfileListView(
ProfileMixin,
PaginatorMixin,
ListView
):
class ProfileListView(ListView):
"""Страница профиля."""
model = User
paginate_by = POST_PER_PAGE
template_name = 'blog/profile.html'
slug_url_kwarg = 'username'

Expand All @@ -162,12 +153,12 @@ def get_context_data(self, **kwargs):


class ProfilUpdateView(
ProfileMixin,
LoginRequiredMixin,
URLProfileMixin,
LoginRequiredMixin,
UpdateView
):
"""Редактивование страници профиля."""
model = User
form_class = UserForm
template_name = 'blog/user.html'
slug_field = 'username'
Expand All @@ -179,12 +170,12 @@ def get_object(self):


class CommentCreateView(
CommentMixin,
LoginRequiredMixin,
URLPostMixin,
LoginRequiredMixin,
CreateView
):
"""Создание комментария."""
model = Comment
posts = None
form_class = CommentForm
pk_url_kwarg = 'post_id'
Expand All @@ -200,20 +191,26 @@ def form_valid(self, form):


class EditCommentUpdateView(
CommentMixin,
CommentDispacthMixin,
LoginRequiredMixin,
URLPostMixin,
LoginRequiredMixin,
UpdateView
):
"""Редактирование комментария."""
model = Comment
form_class = CommentForm
pk_url_kwarg = 'comment_id'
template_name = 'blog/comment.html'


class DeleteCommentDeleteView(
CommentMixin,
CommentDispacthMixin,
LoginRequiredMixin,
URLPostMixin,
LoginRequiredMixin,
DeleteView
):
"""Удаление комментария."""
model = Comment
form_class = CommentForm
pk_url_kwarg = 'comment_id'
template_name = 'blog/comment.html'
Loading

0 comments on commit 761915e

Please sign in to comment.