darklow / django-suit

Modern theme for Django admin interface
http://djangosuit.com/
Other
2.31k stars 701 forks source link

Inline - m2m sortable doesn't work #676

Open arybin93 opened 6 years ago

arybin93 commented 6 years ago

Hello, found this case with m2m relation and sortables inlines:

  1. models.py:
    
    class Label(models.Model):
    """ Store labels """
    text = models.CharField(max_length=20)

class Item(models.Model): """ Store items """ name = models.CharField(max_length=255, db_index=True) label = models.ManyToManyField(Label, blank=True, through='ItemLabel')

class ItemLabel(models.Model): """ Store relations """ item = models.ForeignKey(Item, on_delete=models.CASCADE) label = models.ForeignKey(Label, on_delete=models.CASCADE) order_by = models.PositiveIntegerField(default=0)


admin.py:

class LabelInline(SortableStackedInline): model = ItemLabel sortable = 'order_by' extra = 0

class ItemAdmin(admin.ModelAdmin): """ Item Admin """ inlines = [LabelInline]



All inlines object works correctly, but order_by don't change. All zero.

When I remove default=0, I gоt error after save: “This field is required” 

I tried versions:
- django-suit-0.2.19
- django-suit-0.2.26

Can you help me?
Igotit commented 6 years ago

Same here.

EternalSoul commented 6 years ago

Hey, same here. There's a package called sortedm2m that replaces django's own ManyToManyField and adds some sort of drag and drop sorting, but i didn't manage to try it (mainly because didn't want to add extra package), so i don't know if it works with suit.

I have made small workaround to fix this fast. I have used this on my project also, but this code is provided for OPs models

@receiver(models.signals.post_save, sender=ItemLabel)
def set_order(sender, instance, created, **kwargs):
    if created:
        instance.order_by = ItemLabel.objects.filter(item=instance.item.pk).count() - 1
        instance.save()
EternalSoul commented 6 years ago

I have filled an pull request for a fix.