如何解决如何使用带有额外字段的 Django 模型集?
Here is the example of an inline formset from Django's docs:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author,on_delete=models.CASCADE)
title = models.CharField(max_length=100)
>>> from django.forms import inlineformset_factory
>>> BookFormSet = inlineformset_factory(Author,Book,fields=('title',))
>>> author = Author.objects.get(name='Mike Royko')
>>> formset = BookFormSet(instance=author)
假设我想让某人一次输入多条书评,其中每条书评都针对一本书。 (我将在我的代码中进行查询以获取要审阅的书籍。)
如何显示 BookReview 的表单集(模型表单集?内联表单集?),但在表单上显示一些书籍数据(例如,标题),以便人们知道他们正在审阅哪本书?
所以,模型是
class BookReview(models.Model):
book = models.ForeignKey(Book,on_delete=models.CASCADE)
review_text = models.CharField(max_length=1000)
现在如何初始化formset?下面是一些代码,但根据我的实际示例(不是书评),它进行得并不顺利。
初始化表单集的示例代码(但不完整):
# pick some books to review
# this could change,I don't want to couple it directly to the formset
books_to_review = Book.objects.filter(author=an_author)[:3]
class BookReviewForm(models.ModelForm):
class Meta:
model = BookReview
fields = ('review_text')
# How do I get Book.title (and possibly Book.author.name) into here
# in order to display that info in my template?
formset = forms.modelformset_factory(
BookReview,fields=('review_text'),queryset=BookReview.objects.none(),initial=[{'review_text': '',# more info here? not sure
}
for book in books_to_review])
Django 模板的示例代码:
{% for form in formset %}
{{ form.non_field_errors }}
{# I'd like something like this,suitably styled. #}
{# I believe these won't work,because the form #}
{# doesn't have a "book" field in it #}
<div>Book title: {{ form.book.title.value }}</div>
<div>Author: {{ form.book.author.name.value }}</div>
{{ form.review_text }}
{% endfor %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。