所以我一直在学习 django,我决定制作一个带有评论的博客。这是我的模型:
class Author(models.Model):
name = models.CharField(max_length = 20)
email = models.EmailField(verbose_name = 'e-mail')
def __str__(self):
return self.name
class Post(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=80)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def __str__(self):
return self.title
class Comment(models.Model):
author = models.OneToOneField(Author)
post = models.ForeignKey(Post)
text = models.TextField()
post_date = models.DateTimeField(default = timezone.now)
def __str__(self):
return self.author + "commented"
现在,在我的模板中,我无法访问作者的姓名。它只是显示评论。{{comment.author.name}} 不起作用。
这是模板 block 。
{% extends "base.html" %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<a class="btn btn-default" href="{% url "post_edit" pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
<h1>{{ post.title }}-{{post.author}}</h1>
<p>{{ post.text|linebreaks }}</p>
</div>
{% for comment in comments %}
<div class="post">
<div class="date">
{{ comment.post_date }}
</div>
<h4>Author:{{comment.author.name}}</h4>
<h5>{{ comment.text|linebreaks }}</h5>
</div>
{% endfor %}
<h3>New Comment</h3>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
查看代码
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
author = Author.objects.create()
author.name = request.user
author.email = ""
comment.author = author
comment.post = post
comment.post_date = timezone.now()
comment.save()
return redirect('/posts/'+pk+'/')
else:
form = CommentForm()
comments = Comment.objects.order_by('post_date')
return render(request, 'post_detail.html', {'post': post, 'comments': comments, 'form': form})
问题出在这里:
author = Author.objects.create()
author.name = request.user
author.email = ""
comment.author = author
您创建作者,但不保存姓名和电子邮件。
试试这个:
author = Author.objects.create(name=request.user, email="")
comment.author = author
或者这个:
author = Author.objects.create()
author.name = request.user
author.email = ""
author.save()
comment.author = author.pk
我是一名优秀的程序员,十分优秀!