Django - 显示ModelForm外键字段

时间:2012-04-26 11:30:51

标签: django django-models django-forms

型号&表格

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

如何显示作者的名字?

2 个答案:

答案 0 :(得分:10)

这应该有效:

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

但您不能使用此表单创建书籍,仅用于更新,如果未在实例上设置authos,则无法使用此表单。

答案 1 :(得分:0)

如何创建只读字段?

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方法可以防止恶意请求试图覆盖作者。