Django - 显示一个ModelForm外键字段 [英] Django - Display a ModelForm foreign key field

查看:1688
本文介绍了Django - 显示一个ModelForm外键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Book(models.Model):
  author = models.ForeignKey(User)
  name = models.CharField(max_length=50)

class BookForm(forms.ModelForm):
  class Meta:
    model = Book
    widgets = {
      'author': forms.HiddenInput(),
    }

允许更改作者

但我想显示他的名字

<form action="/books/edit" method="post">{% csrf_token %}
  {{ form.author.label }}: {{ form.author.select_related.first_name }}
  {{ form.as_p }}
</form>



问题



当然 form.author.select_related.first_name 不工作

如何显示作者的第一个名字?

How can I display the firstname of the author ?

推荐答案

这应该可以工作:

<form action="/books/edit" method="post">{% csrf_token %}
  {{ form.author.label }}: {{ form.instance.author.first_name }}
  {{ form.as_p }}
</form>

但是,您无法使用此表单创建图书,仅用于更新,如果authos没有设置实例。

But you cannot use this form for creating books, only for updating, this won't work if the authos is not set on instance.

这篇关于Django - 显示一个ModelForm外键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆