django_select2,Model对象不可迭代

时间:2015-07-30 15:32:28

标签: python django modelform

我正在收到"'文件'对象不可迭代"提交此表单时出错。如果'记录'是从模型中取出而不是用select2包写的。它与django_select2包中的示例代码非常相似。我已经尝试过将它变成Document.objects.all(),而且它也没有用。

models.py

class Individual(models.Model):
    id = models.CharField(max_length=8, unique=True, verbose_name='ID')
    first_name = models.CharField(max_length=50, null=True)
    middle_name = models.CharField(max_length=50, blank=True, null=True)
    last_name = models.CharField(max_length=100, null=True)
    dob = models.CharField(max_length=15, blank=True)
    suffix = models.CharField(max_length=25, blank=True, null=True)

    time_stamp = models.DateTimeField(auto_now=True)
    entered_by = models.CharField(max_length=50)

    def _name(self):
        return self.first_name + ' ' + self.last_name

    class Meta:
        db_tablespace = 'name_of_database'

    def __unicode__(self):
        return self.id

class Document(models.Model):
    document_name = models.CharField(max_length=100)

    class Meta:
        db_tablespace = 'name_of_database'

    def __unicode__(self):
        return self.document_name

class DocLog(models.Model):

    individual = models.ForeignKey('Individual', to_field='id', null=True)
    fiscal = models.PositiveIntegerField(db_index=True)
    document = models.ManyToManyField(Document, max_length=50,    
    verbose_name='Document Title')
    date_received = models.DateField(editable=True, verbose_name='Date Received')
    doc_notes = models.TextField(max_length=500, verbose_name='Document Notes')
    time_stamp = models.DateTimeField(auto_now=True)
    entered_by = models.CharField(max_length=50)

    class Meta:
        db_tablespace = 'name_of_database'
        verbose_name = 'Document Log'

    def __unicode__(self):
        return self.individual.id

forms.py

from django import forms
from django_select2 import *
from .models import DocLog, Document

#Document Select2 class
class DocumentChoices(AutoModelSelect2Field):
    queryset = Document.objects
    search_fields = ['document_name__icontains',]

#New document form
class NewDocument(forms.ModelForm):

    document = DocumentChoices()

    class Meta:

        model = DocLog
        fields = ('individual', 'fiscal', 'document', 'date_received', 'doc_notes')

        widgets = {
            'individual': forms.HiddenInput(),
        }

1 个答案:

答案 0 :(得分:0)

您在模型中定义了ManyToManyField,在Modelform中,ManyToManyField由django.forms.ModelMultipleChoiceField表示,它是一个MultipleChoiceField,其选择是模型QuerySet。

因此,您使用AutoModelSelect2MultipleField

而不是使用AutoModelSelect2Field

适合您的情况

#Document Select2 class
class DocumentChoices(AutoModelSelect2MultipleField):
    queryset = Document.objects
    search_fields = ['document_name__icontains',]