There is an application posts. There is a model:
class Post(models.Model):
text = models.TextField()
pub_date = models.DateTimeField("date published", auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts")
group = models.ForeignKey(Group, on_delete=models.SET_NULL, related_name="posts", blank=True, null=True)
def __str__(self):
# выводим текст поста
return self.text
There is a urls:
path('posts/<str:username>/<int:post_id>/', views.post_view, name='post'),
There is a views:
@login_required
def post_edit(request, username, post_id):
post = get_object_or_404(Post, pk=post_id, author__username=username)
print(post.text)
if request.user != post.author:
return redirect('post', username=username, post_id=post_id)
form = PostForm(request.POST or None, instance=post)
if form.is_valid():
form.save()
return redirect('post', username=username, post_id=post_id)
return render(request, 'post_new.html', {'form': form, 'post': post})
When checking here in Views everything is displayed correctly: print(post.text). However, nothing works on the HTML page?
There is a HTML:
<main role="main" class="container">
<div class="row">
<div class="col-md-12">
<div class="card mb-3 mt-1 shadow-sm">
<div class="card-body">
<p class="card-text">
<a href="{% url 'profile' user.username %}">
<strong class="d-block text-gray-dark">@{{ post.author.username }}</strong>
</a>
{{ post.text }}
</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<p>Author: {{ post.author.get_full_name }}</p>
<p>ID: {{ post.author.username }}</p>
</div>
<small class="text-muted">{{ post.pub_date }}</small>
</div>
</div>
</div>
</div>
</div>
</main>
What is the problem. Nothing works here? post.pub_date, post.author.get_full_name... Why does this work in context:
{% for post in posts %}
....
{{post.text}}
...
Works through {{ posts.0.author.username }}. But it doesn't work: {{ post.author.username }}.
What am I doing wrong?
If you use
Modelmame.Objects.filterto generatepostscontext variable, it (posts) become a list. So you need to use below syntax.If you use
Modelmame.Objects.getto generatepostscontext variable, it (posts) become a one object. So you need to use below syntax.