from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
description = models.CharField(max_length=200)
image = models.ImageField(upload_to='images/%Y/%m/%d/', blank=True)
date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.description
class Meta:
ordering = ['-date']
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
text = models.TextField()
created = models.DateTimeField(default=timezone.now, null=True)
moderation = models.BooleanField(default=False)
def __str__(self):
return self.text
{% extends "base.html" %}
{% block title %}Псоты{% endblock %}
{% block content %}
{% for post in posts %}
<div class="card">
<div class="row align-items-center p-2">
<div class="col-2 card-img-div">
<img class='author-image' src="{{ post.author.profile.photo.url }}">
</div>
<div class="col-10">
<h5 class="card-title">{{ post.author }}</h5>
</div>
</div>
<div class="">
<img src="{{ post.image.url }}" class="card-img-top">
</div>
<div class="">
<p class="card-text p-2">{{ post.author }}: {{ post.description }}</p>
</div>
<div class="">
{% for comment in comments %}
{{ comment }}
{% endfor %}
</div>
<div class="">
<form action="" method="POST">
{% csrf_token %}
{{ form }}
<button type="submit" name="button">Отправить</button>
</form>
</div>
<div class="">
<p class="card-text p-2"><small class="text-muted">{{ post.date }}</small></p>
</div>
</div>
{% endfor %}
{% endblock %}
{% block aside %}
Боковая
{% endblock %}
from django.shortcuts import render
from .models import Post,Comment
from .forms import CommentForm
def home(request):
posts = Post.objects.all()
# if request.method == 'POST':
# form = CommentForm(request.POST)
# if form.is_valid():
# form = form.save(commit=False)
# form.user = request.user
# form.post = posts
# form.save()
# else:
# comments = Comment.objects.filter()
# form = CommentForm()
return render(request, 'blog/index.html', {'posts': posts,'comments':comments,'form':form})
from django.core.exceptions import ObjectDoesNotExist
def home(request):
if request.method == 'POST':
id = request.POST.get('id', None)
if id:
try:
post = Post.objects.get(pk=id)
except ObjectDoesNotExist:
return () # обработка ошибки пост не найден
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.post = post
form.save()
return () # все хорошо, коммент сохранен
return () # обработка ошибки форма не валидная
return () # обработка ошибки id не передан
# else здесь не обязательно писать код выполнится только если не ПОСТ
context = {
'form': CommentForm(),
'comments': Comment.objects.filter(moderation=True)
}
return (request, 'blog/index.html', context) # return метод GET
comments = Comment.objects.all()
comments = Comment.objects.filter(moderation=True)
from django.contrib.auth import get_user_model
User = get_user_model()
from name_app.models import Post, Comment # после запятой пробел