TreeNodeChoiceField在表单Django中不可迭代



我想知道是否有人熟悉Django中mptt中的TreeNodeChoiceField。我正试图在一个表单中使用这个功能来在博客上发布文章。但当我尝试创建一个新的帖子时,它说关联的对象是不可迭代的。get方法或当我简单地使用表单时不会发生这种情况。ModelMultipleChoiceField。因此,我想知道是否有人知道我如何在没有这个问题的情况下使用TreeNodeChoiceField。感谢您的意见!!

这是表格.py

class BlogForm(forms.ModelForm):
sdg = forms.ModelMultipleChoiceField(
queryset=SDG.objects.all(),
widget=forms.CheckboxSelectMultiple
)
value_chain = TreeNodeChoiceField(queryset=Value_chain.objects.all())
industry = forms.ModelMultipleChoiceField(
queryset=Industry.objects.all()
)
class Meta:
model = Blog
fields = ["title", "sdg", "value_chain", "industry", "contenu"]

这是我的看法.py

def blog_create(request):
if request.method == "POST":
blog_form = BlogForm(request.POST)
docu_form = DocumentFormBlog(request.POST, request.FILES)
if blog_form.is_valid() and docu_form.is_valid(): 
blog_form.instance.user = request.user
blog = blog_form.save()
docu_form.instance.blog_related = blog
docu_form.save()
messages.success(request, 'Your blog was successfully created!')
return redirect('knowledge:search_blog')
else:
messages.error(request, 'Please correct the error below.')
else:
blog_form = BlogForm(request.POST)
docu_form = DocumentFormBlog(request.POST, request.FILES)
return render(request, "dist/inside/knowledge/blog/create_blog.html", context={"blog_form": blog_form, "docu_form": docu_form})

最后,为了使它发挥作用,我不得不创建一个新表单,只用于TreeNodeChoiceField,它将调用适当的Model:

"quot">

class SeedFormVC(forms.ModelForm):
value_chain = TreeNodeChoiceField(queryset=Value_chain.objects.all().exclude(id=1))
class Meta:
model = Value_Chain_Seed
fields = ['value_chain']

"quot">

这不是最好的答案,所以如果有人找到更好的答案,请告诉我!

最新更新