简体   繁体   English

TreeNodeChoiceField 在表单中不可迭代 - Django

[英]TreeNodeChoiceField not iterable in a form - Django

I was wondering if someone was familiar with TreeNodeChoiceField from mptt in Django.我想知道是否有人熟悉 Django 中 mptt 的 TreeNodeChoiceField。 I am trying to use this feature in a form to post an article on a blog.我正在尝试在表单中使用此功能在博客上发布文章。 But when I try to create a new post it says that the object associated is not iterable.但是当我尝试创建一个新帖子时,它说关联的 object 是不可迭代的。 This doesn't happen with a get method or when I simply use a forms.ModelMultipleChoiceField.使用 get 方法或仅使用 forms.ModelMultipleChoiceField 时不会发生这种情况。 I was thus wondering if someone knew how I could use TreeNodeChoiceField without this issue.因此,我想知道是否有人知道我如何在没有这个问题的情况下使用 TreeNodeChoiceField。 Thank you for any input!!感谢您的任何意见!

Here is the forms.py这是 forms.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"]

and here is my views.py这是我的views.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})

In the end, to make it work, I had to create a new form, only for the TreeNodeChoiceField that would call the appropriate Model:最后,为了让它工作,我必须创建一个新表单,仅用于调用适当 Model 的 TreeNodeChoiceField:

""" """

class SeedFormVC(forms.ModelForm):
    value_chain = TreeNodeChoiceField(queryset=Value_chain.objects.all().exclude(id=1))

    class Meta:
        model = Value_Chain_Seed
        fields = ['value_chain']

""" """

This is not the best answer, so if anyone finds something better, please let me know!这不是最好的答案,所以如果有人发现更好的东西,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM