Hi there,
I have implemented a AutoCompleteSelectedField for selecting a ForeignKey related object in a django.admin form. Now I would like to add the nice little green "Plus" button that allows the user to directly add a new object of this type and then come back to the original form. According to the django-selectable manual, this should be possible (Quote):
"
The django-selectable widgets are compatitible with the add another popup in the
admin. It’s that little green plus sign that appears next to
ForeignKey or
ManyToManyField items. This makes django-selectable a user friendly replacement
for the
ModelAdmin.raw_id_fields
when the default select box grows too long.
"
Could anyone give me an example for actually getting this done? I "kind of" got this working but the problem is that my popup window is not closing and the new object is not entered into the SelectedField. So the last part of the process is going wrong. Here is what I did (simplified, leaving out bits):
****************
***models.py::
class DnaComponent(models.Model):
name = models.CharField('Name', max_length=200, blank=True)
displayId = models.CharField('ID', max_length=20, unique=True)
insert = models.ForeignKey( 'self', blank=True, null=True, related_name='Insert')
...
***************
***forms.py::
from selectable.base import ModelLookup
from selectable.registry import registry
import selectable.forms as sforms
class InsertLookup(ModelLookup):
model = DnaComponent
search_fields = ('displayId__startswith', 'name__icontains')
def get_item_id(self,item):
return
item.pkregistry.register(InsertLookup)
class DnaComponentForm(forms.ModelForm):
insert = sforms.AutoCompleteSelectField(lookup_class=InsertLookup, required=False)
class Meta:
model = DnaComponent
***************
***admin.py::
class DnaComponentAdmin( admin.ModelAdmin ):
form = DnaComponentForm
def get_form(self, request, obj=None, **kwargs):
field = form.base_fields['insert']
if not isinstance(field.widget, RelatedFieldWidgetWrapper ):
relation = DnaComponent._meta.get_field('insert').rel
field.widget.choices = [] ## workaround to simulate choicefield
field.widget = RelatedFieldWidgetWrapper( field.widget, relation, self.admin_site )
Any idea how this can be fixed?
Thanks a lot in advance,
Greetings,
Raik