且构网

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

ListField 的 Django-nonrel 表单字段

更新时间:2023-10-05 23:42:16

好的,这是我为使这一切正常工作所做的...我从头开始

OK, here is what I did to get this all working ... I'll start from the beginning

这就是我的模型的样子

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

我希望能够使用管理界面使用列表字段的多选小部件来创建/编辑此模型的实例.因此,我创建了一些自定义类,如下

I wanted to be able to use the admin interface to create/edit instances of this model using a multiple select widget for the list field. Therefore, I created some custom classes as follows

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

这些类允许在管理员中使用列表字段.然后我创建了一个表单以在管理站点中使用

These classes allow the listfield to be used in the admin. Then I created a form to use in the admin site

class MyClassForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyClasstForm,self).__init__(*args, **kwargs)
        self.fields['field'].widget.choices = [(i.pk, i) for i in AnotherClass.objects.all()]
        if self.instance.pk:
            self.fields['field'].initial = self.instance.field

    class Meta:
        model = MyClass

完成此操作后,我创建了一个管理模型并将其注册到管理站点

After having done this I created a admin model and registered it with the admin site

class MyClassAdmin(admin.ModelAdmin):
    form = MyClassForm

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

admin.site.register(MyClass, MyClassAdmin)

这现在在我的代码中工作.请记住,这种方法可能根本不适合 google_appengine,因为我不太熟悉它的工作原理,而且它可能会创建低效的查询.

This is now working in my code. Keep in mind that this approach might not at all be well suited for google_appengine as I am not very adept at how it works and it might create inefficient queries an such.