如果有情况,我需要一个带有动态选择选项的表单集。 假设我有3个模型Book-> Chapter-> Comment
# ============ models.py =============
class Book(models.Model):
name = models.CharField(_("Book name"), max_length=50)
class Meta:
verbose_name = _("book")
verbose_name_plural = _("books")
def __str__(self):
return self.name
class Chapter(models.Model):
name = models.CharField(_("Chapter name"), max_length=50)
book = models.ForeignKey(Book, verbose_name=_(""), on_delete=models.CASCADE)
class Meta:
verbose_name = _("chapter")
verbose_name_plural = _("chapters")
def __str__(self):
return self.name
class Comment(models.Model):
comment = models.TextField(_("Chapter comment"))
chapter = models.ForeignKey(Chapter, verbose_name=_("Chapter"), on_delete=models.CASCADE)
class Meta:
verbose_name = _("Comment")
verbose_name_plural = _("Comments")
def __str__(self):
return self.name
# ============ Forms.py =============
class CommentForm(forms.Form):
chapter = forms.ModelChoiceField(Chapter.objects.all()) # <~~~~ Here is the problem
comment = forms.CharField(max_length=50, required=True)
。我有一个页面网址'/ book / {id} / comment' ,在此URL中,用户将使用表单集+ jQuery处理addrow按钮对一个或多个章节进行评论。
如何过滤(章节的)查询集以匹配我在ID中选择的书中的章节?