1

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

ListField 的 Django-nonrel 表单字段

按照接受的答案

模型.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

管理员.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'>
4

1 回答 1

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 的工作原理、如何导入模块等。

于 2011-10-25T15:05:41.297 回答