【问题标题】:Django - Display a ModelForm foreign key fieldDjango - 显示 ModelForm 外键字段
【发布时间】:2012-04-26 11:30:50
【问题描述】:

型号和形式

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 不起作用

如何显示作者的名字?

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:

    这应该可行:

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

    但是这个表单不能用于创建书籍,只能用于更新,如果作者没有设置在实例上,这将不起作用。

    【讨论】:

      【解决方案2】:

      创建一个只读字段怎么样?

      class BookForm(forms.ModelForm):
          def __init__(self, *args, **kwargs):
              super(BookForm, self).__init__(*args, **kwargs)
              instance = getattr(self, 'instance', None)
              if instance and instance.id:
                  self.fields['author'].widget.attrs['readonly'] = True
      
          def clean_author(self):
              return self.instance.author
      
          class Meta:
              model = Book
              widgets = {
                 'author': forms.TextInput(),
              }
      

      clean_author 方法用于防止恶意请求试图覆盖作者。

      【讨论】:

      • 显示作者的id
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2014-04-05
      • 2018-06-25
      • 2014-09-02
      • 2011-08-08
      • 2013-05-31
      相关资源
      最近更新 更多