gpt4 book ai didi

python - 如何在 django 中获取外键的特定字段?

转载 作者:太空宇宙 更新时间:2023-11-03 17:24:31 25 4
gpt4 key购买 nike

所以我一直在学习 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

关于python - 如何在 django 中获取外键的特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32747018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com