且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django与Mongodb listfield不相关

更新时间:2022-10-18 13:09:20

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



由于它很常见:

 从django导入表单

你可能只想编辑下面的代码:

 #你必须弄清楚如何为自己导入Mongo ListField :) 
class ModelListField(ListField):
def formfield(self,** kwargs):
return FormListField(** kwargs)

class ListFieldWidget(forms.SelectMultiple):
pass

class FormListField(forms.MultipleChoiceField):

这是一个自定义窗体字段,可以显示一个ModelListField作为多选择GUI元素

widget = ListFieldWidget

def clean(self,value):
#TODO:清理你的数据无论你的情况如何,在任何方式都是正确的,并返回清理的数据,而不是仅仅
的返回值

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


I am trying to implement manytomany field relation in django-nonrel on mongodb. It was suggessted at to:

Django-nonrel form field for ListField

Following the accepted answer

models.py

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

i am not sure where the following goes, it has been tested in 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)

The following Errors keep popping up:

If the middle custom class code is used in models.py

name 'SelectMultiple' is not defined

If custom class code is taken off models.py:

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

You just need to import SelectMultiple by the sound of it. You can put the code in any of those three files, fields.py would make sense.

Since it's pretty usual to have:

from django import forms

at the top of your file already, you probably just want to edit the code below to:

# 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

You probably also want to try and learn a bit more about how python works, how to import modules etc.