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

时间:2015-09-23 18:36:14

标签: python django django-models django-templates

所以我一直在学习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}}不起作用。

这是模板块。

{% 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 %}

ViewCode

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})

1 个答案:

答案 0 :(得分:1)

问题在于:

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