django-ajax-selects raises Exception object not found for many to many admin inline

345 Views Asked by At

I am using django-ajax-selects to facilitate user input in Django admin; specifically in a many to many relation where the 'through' model is inlined:

models.py

class Part(models.Model):
    item_code = models.CharField(max_length=100, primary_key=True)
    name = models.CharField('Part Name', max_length=128)

    def __unicode__(self):
        return self.item_code


class Service(models.Model):
    parts = models.ManyToManyField(Part, through='ServicePart')

class ServicePart(models.Model):
    STATE_CHOICES = (
        ('N', 'New'),
        ('U', 'Used'),
    )
    service = models.ForeignKey(Service)
    part = models.ForeignKey(Part)

    cost = models.DecimalField ...
    state = models.CharField(max_length=1, choices=STATE_CHOICES)

admin.py

class ServicePartInline(AjaxSelectAdminTabularInline):

    model = ServicePart

    form = make_ajax_form(ServicePart, {
            #item_code is a lookup channel
            'part': 'item_code', 
             },
           show_help_text=True)

    extra = 2

class ServiceAdmin(admin.ModelAdmin):
    inlines = [ServicePartInline,]

lookups.py

class PartLookup(LookupChannel):

    model = Part

    def get_query(self, q, request):
        return Part.objects.filter(Q(item_code__icontains=q) | Q(name__istartswith=q)).order_by('name')

    def get_result(self, obj):
        return obj.name

    def format_match(self, obj):
        return u"%s<div><i>%s</i></dev>" % (escape(obj.item_code), escape(obj.name))

    def format_item_desplay(self, obj):
        return u"%s<div><i>%s</i></dev>" % (escape(obj.item_code), escape(obj.name))

setting.py

AJAX_LOOKUP_CHANNELS = {
    'item_code': ('appname.lookups', 'PartLookup'),
}

Now everything works fine (choosing many parts within the service admin) until I hit save; I get the following exception:

appname.lookups.PartLookup object at 0x7f28742e5fd0> cannot find object:6965933

6965933 is the code of the part I selected inside the service admin ...

I don't understand what is causing this exception.

Your help is appreciated

1

There are 1 best solutions below

0
On

It turned out the problem is caused from the Part model not having an auto id as primary key. Once I added the auto primary key by altering the database and modified item_code to be unique and not primary key, the problem was solved.

After the above, you need to take care of models that have relation with the Part model, because the relation was referenced using the item_code and not the newly added id.