/
piligrim
/
Python_Django_Learn
Обзор
Документация
Войти
/
piligrim
/
Python_Django_Learn
Код
Запросы
1
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
pull_request
src/blog/views.py
82 строки
3 KB
piligrim
14_add_user_model
22 май 2025, 15:16
22 май 2025, 15:16
a6e3f7b
Код
Авторство
О чём код?
from django.shortcuts import render, redirect from .models import Post, Author, Comment from datetime import date from blog.forms import CommentForm def posts(request): all_posts = Post.objects.prefetch_related('comments').all() comment_form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post_id = request.POST.get('post_id') comment.save() return redirect('posts') context = { 'title': 'Мой блог', 'posts': all_posts, 'comment_form': comment_form, } return render(request, 'blog/posts.html', context) def create_post(request): # Получение данных из формы if request.method == "POST": # Извлекаем данные из POST-запроса title = request.POST.get("title") # Значение поля "title" text = request.POST.get("text") # Значение поля "text" author = request.user # Текущий авторизованный пользователь # Проверка на то что заполнены все поля if author and title and text: # Создаем новый пост в базе данных Post.objects.create( author=author, title=title, text=text ) # Перенаправляем пользователя на список постов return redirect("posts") # Если все хорошо то # Делаем перенаправление на страницу с постами # Здесь можно прикрутить обработку ошибок # Если запрос GET - показываем пустую форму return render(request, "blog/post_form.html") def author_list(request): authors = Author.objects.all() context = {'authors': authors} return render(request, 'blog/authors.html', context) def create_author(request): if request.method == "POST": # Извлекаем данные из POST-запроса last_name = request.POST.get('last_name') first_name = request.POST.get('first_name') middle_name = request.POST.get('middle_name', None) birth_date = date.fromisoformat(request.POST.get('birth_date')) email = request.POST.get('email') today = date.today() age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day)) author = Author( last_name=last_name, first_name=first_name, middle_name=middle_name, birth_date=birth_date, email=email, age=age ) author.save() return redirect("author_list") return render(request, "blog/create_author.html")