Django-nonrel form field for ListField

前端 未结 4 1693
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 09:21

I\'m experimenting with django-nonrel on appengine and trying to use a djangotoolbox.fields.ListField to implement a many-to-many relation. As I re

4条回答
  •  醉话见心
    2020-12-08 09:30

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

    This is what what my model looked like

    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)
    

    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.

提交回复
热议问题