Django-Nonrel与Mongodb listfield

时间:2011-10-16 05:23:00

标签: mongodb django-admin django-nonrel listfield

我正在尝试在mongodb上的django-nonrel中实现多个字段关系。有人建议:

Django-nonrel form field for ListField

按照接受的答案

models.py

class MyClass(models.Model):
    field = ListField(models.ForeignKey(AnotherClass))

我不知道下面的地方,它已在fields.py,widgets,py,models.py

中测试过
class ModelListField(ListField):
    def formfield(self, **kwargs):
    return FormListField(**kwargs)

class ListFieldWidget(SelectMultiple):
    pass

class FormListField(MultipleChoiceField):
    """
    This is a custom form field that can display a ModelListField as a Multiple Select GUI element.
    """
    widget = ListFieldWidget

    def clean(self, value):
    #TODO: clean your data in whatever way is correct in your case and return cleaned data instead of just the value
    return value

admin.py

class MyClassAdmin(admin.ModelAdmin):
    form = MyClassForm

    def __init__(self, model, admin_site):
    super(MyClassAdmin,self).__init__(model, admin_site)

admin.site.register(MyClass, MyClassAdmin)

以下错误不断出现:

如果在models.py中使用中间自定义类代码

name 'SelectMultiple' is not defined

如果自定义类代码取自models.py:

No form field implemented for <class 'djangotoolbox.fields.ListField'>

1 个答案:

答案 0 :(得分:0)

你需要通过它的声音导入SelectMultiple。您可以将代码放在这三个文件中的任何一个中,fields.py就有意义了。

因为通常有:

from django import forms

在您的文件顶部,您可能只想编辑以下代码:

# you'll have to work out how to import the Mongo ListField for yourself :)
class ModelListField(ListField):
    def formfield(self, **kwargs):
    return FormListField(**kwargs)

class ListFieldWidget(forms.SelectMultiple):
    pass

class FormListField(forms.MultipleChoiceField):
    """
    This is a custom form field that can display a ModelListField as a Multiple Select GUI element.
    """
    widget = ListFieldWidget

    def clean(self, value):
    #TODO: clean your data in whatever way is correct in your case and return cleaned data instead of just the value
    return value

您可能还想尝试更多地了解python如何工作,如何导入模块等。