Giter VIP home page Giter VIP logo

django-sortedm2m's Introduction

django-sortedm2m

Jazzband PyPI Release Build Status Code coverage

sortedm2m is a drop-in replacement for django's own ManyToManyField. The provided SortedManyToManyField behaves like the original one but remembers the order of added relations.

Use Cases

Imagine that you have a gallery model and a photo model. Usually you want a relation between these models so you can add multiple photos to one gallery but also want to be able to have the same photo on many galleries.

This is where you usually can use many to many relation. The downside is that django's default implementation doesn't provide a way to order the photos in the gallery. So you only have a random ordering which is not suitable in most cases.

You can work around this limitation by using the SortedManyToManyField provided by this package as drop in replacement for django's ManyToManyField.

Requirements

django-sortedm2m runs on Python 3.6+ and multiple Django versions. See the .github/workflows/test.yml configuration for the tested Django versions.

Usage

Use SortedManyToManyField like ManyToManyField in your models:

from django.db import models
from sortedm2m.fields import SortedManyToManyField

class Photo(models.Model):
    name = models.CharField(max_length=50)
    image = models.ImageField(upload_to='...')

class Gallery(models.Model):
    name = models.CharField(max_length=50)
    photos = SortedManyToManyField(Photo)

If you use the relation in your code like the following, it will remember the order in which you have added photos to the gallery. :

gallery = Gallery.objects.create(name='Photos ordered by name')
for photo in Photo.objects.order_by('name'):
    gallery.photos.add(photo)

SortedManyToManyField

You can use the following arguments to modify the default behavior:

sorted

Default: True

You can set the sorted to False which will force the SortedManyToManyField in behaving like Django's original ManyToManyField. No ordering will be performed on relation nor will the intermediate table have a database field for storing ordering information.

sort_value_field_name

Default: 'sort_value'

Specifies how the field is called in the intermediate database table by which the relationship is ordered. You can change its name if you have a legacy database that you need to integrate into your application.

base_class

Default: None

You can set the base_class, which is the base class of the through model of the sortedm2m relationship between models to an abstract base class containing a __str__ method to improve the string representations of sortedm2m relationships.

Note

You also could use it to add additional fields to the through model. But please beware: These fields will not be created or modified by an automatically created migration. You will need to take care of migrations yourself. In most cases when you want to add another field, consider not using sortedm2m but use a ordinary Django ManyToManyField and specify your own through model.

Migrating a ManyToManyField to be a SortedManyToManyField

If you are using Django's migration framework and want to change a ManyToManyField to be a SortedManyToManyField (or the other way around), you will find that a migration created by Django's makemigrations will not work as expected.

In order to migrate a ManyToManyField to a SortedManyToManyField, you change the field in your models to be a SortedManyToManyField as appropriate and create a new migration with manage.py makemigrations. Before applying it, edit the migration file and change in the operations list migrations.AlterField to AlterSortedManyToManyField (import it from sortedm2m.operations). This operation will take care of changing the intermediate tables, add the ordering field and fill in default values.

Admin

SortedManyToManyField provides a custom widget which can be used to sort the selected items. It renders a list of checkboxes that can be sorted by drag'n'drop.

To use the widget in the admin you need to add sortedm2m to your INSTALLED_APPS settings, like:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',

    'sortedm2m',

    '...',
)

Otherwise it will not find the css and js files needed to sort by drag'n'drop.

Finally, make sure not to have the model listed in any filter_horizontal or filter_vertical tuples inside of your ModelAdmin definitions.

If you did it right, you'll wind up with something like this:

http://i.imgur.com/HjIW7MI.jpg

It's also possible to use the SortedManyToManyField with admin's raw_id_fields option in the ModelAdmin definition. Add the name of the SortedManyToManyField to this list to get a simple text input field. The order in which the ids are entered into the input box is used to sort the items of the sorted m2m relation.

Example:

from django.contrib import admin

class GalleryAdmin(admin.ModelAdmin):
    raw_id_fields = ('photos',)

Contribute

This is a Jazzband project. By contributing you agree to abide by the Contributor Code of Conduct and follow the guidelines.

You can find the latest development version on Github. Get there and fork it, file bugs or send well wishes.

Running the tests

I recommend to use tox to run the tests for all relevant python versions all at once. Therefore install tox with pip install tox, then type in the root directory of the django-sortedm2m checkout:

tox

The tests are run against SQLite, then against PostgreSQL, then against mySQL - so you need to install PostgreSQL and mySQL on your dev environment, and should have a role/user sortedm2m set up for both PostgreSQL and mySQL.

Code Quality

This project uses isort, pycodestyle, and pylint to manage validate code quality. These validations can be run with the following command:

tox -e quality

django-sortedm2m's People

Contributors

akaihola avatar alancoding avatar appden avatar awais786 avatar benthompson avatar cchurch avatar clintonb avatar dragoonaethis avatar fcurella avatar gorandev avatar gregmuellegger avatar jayvdb avatar jezdez avatar jlemaes avatar johnraz avatar mikeknoop avatar mitchellrj avatar mystic-mirage avatar nemesifier avatar ninjadero avatar outime avatar quantum5 avatar richardbarran avatar rohithasrk avatar rolandgeider avatar seanoc avatar smcoll avatar tipuch avatar vchrisb avatar vxsx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-sortedm2m's Issues

Limiting items count

This is example from description:

from django.db import models
from sortedm2m.fields import SortedManyToManyField

class Photo(models.Model):
    name = models.CharField(max_length=50)
    image = models.ImageField(upload_to='...')

class Gallery(models.Model):
    name = models.CharField(max_length=50)
    photos = SortedManyToManyField(Photo)

So, what if Photo model contains 100,000 items. Will be generated 100,000 <input type="checkbox"> in admin interface? As shows my practice, this leads to hang the browser.

Enhancement: Flag to allow duplicate model entries.

Hi,

It would be great if having duplicate model entries in a SortedManyToManyField could be enabled. Perhaps an optional flag like say allow_duplicates that defaults to False could be used?

Cheers,
Lewis

South's --auto doesn't work for ManyToManyField -> SortedManyToManyField

If I have a Poll model with a questions = models.ManyToManyField(Question), and I change the field into a SortedManyToManyField, South doesn't detect the change:

$ ./manage.py schemamigration --auto polls
Nothing seems to have changed.

This is Django pre-1.5, django-sortedm2m 0.4.0 and South 0.7.6.

using raw_id_fields, ordering cannot be changed

i have a SortedManyToManyField listed in my ModelAdmin's raw_id_fields. Adding and removing IDs works perfectly, but changing the order of the IDs does not work; when the form is saved, the original sort order is retained.

Missing javascript method html_unescape.

When adding an element to a sortedm2m field through the admin (through a popup).
When saving the instance the popup doesn't close, and there is this single error in the javascript console:
ReferenceError: html_unescape is not defined (widget.js:91:17).
It apparently can't find the html_unescape javascript function for some reason.

tested with Django1.10.3, django-sortedm2m==1.3.2

if (window.showAddAnotherPopup) { var django_dismissAddAnotherPopup = window[dismissPopupFnName]; window[dismissPopupFnName] = function (win, newId, newRepr) { // newId and newRepr are expected to have previously been escaped by // django.utils.html.escape. newId = html_unescape(newId);

Provide ``save=False`` feature for autofixture

It would be splendid if one could provide a save boolean when creating the fixture, to not save the test data immediately to the database.

In my case I'm using AutoFixture for test cases, and within the test_addData() TestCase I'd like to generate the data via autofixture, but the actual creation should be done by the functionality being tested.

Example:
fixture = AutoFixture(Data, field_values={'unique_id': '12345'})
fixture.create(1, autosave=False)

Cheers
Fabian

1.7 Migration: RuntimeError: Conflicting 'gallery_photos' models in application 'my_app'

I've got a runtime error after creating Gallery and Photo models, and making migrations. I'm using Django 1.7b4.
I hope it will help.

# my_project/my_app/models.py

from django.db import models
from django_extensions.db.models import TimeStampedModel
from sortedm2m.fields import SortedManyToManyField

class Event(TimeStampedModel):
    name = models.CharField(_("name"), max_length=255, blank=True)
    start = models.DateTimeField(_("start"))
    …

    class Meta:
        verbose_name = _("event")
        verbose_name_plural = _("events")

    def __unicode__(self):
        return self.name


class Gallery(TimeStampedModel):
    event = models.OneToOneField('my_app.Event',
            verbose_name=_("event"), on_delete=models.PROTECT)
    photos = SortedManyToManyField('my_app.Photo')

    class Meta:
        verbose_name = _("Gallery")
        verbose_name_plural = _("Galleries")

    def __unicode__(self):
        name = self.event.name
        start = self.event.start.strftime('%d %B %Y')
        return name + " (" + start + ")"


class Photo(TimeStampedModel):
    legend = models.CharField(_("legend"), max_length=255, blank=True)
    image = models.ImageField(upload_to="photo/%Y/%m/")

    class Meta:
        verbose_name = _("Photo")
        verbose_name_plural = _("Photos")

    def __unicode__(self):
        return self.legend

After adding Gallery and Photo model class:

$ dj makemigrations my_app

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 427, in execute_from_command_line
    utility.execute()
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 419, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 337, in execute
    output = self.handle(*args, **options)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 97, in handle
    changes = autodetector.changes(graph=loader.graph, trim_to_apps=app_labels or None)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 36, in changes
    changes = self._detect_changes()
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 54, in _detect_changes
    new_apps = self.to_state.render()
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 64, in render
    model.render(self.apps)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 270, in render
    body,
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 171, in __new__
    new_class.add_to_class(obj_name, obj)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 303, in add_to_class
    value.contribute_to_class(cls, name)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/sortedm2m/fields.py", line 247, in contribute_to_class
    self.rel.through = create_sorted_many_to_many_intermediate_model(self, cls)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/sortedm2m/fields.py", line 73, in create_sorted_many_to_many_intermediate_model
    '_to_field_name': to,
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 289, in __new__
    new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
  File "/home/batisteo/my_project/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 201, in register_model
    (model_name, app_label, app_models[model_name], model))
RuntimeError: Conflicting 'gallery_photos' models in application 'my_app': <class 'my_app.models.Gallery_photos'> and <class 'Gallery_photos'>.

Thumbnails in admin template?

Is there a simple way to display thumbnails in the admin interface? I've set str() to return an anchor tag with appropriate href (as I've done in the rest of admin), but it gets escaped by your template. This seems like an important feature, since dragging and dropping a list of filenames is far from optimal in the case of a photo gallery.

Self-referential Sorted M2M has parent included

Using a model such as:

class MenuItem(models.Model):
    title = models.CharField(max_length=255)
    children = SortedManyToManyField('self')

Seems to almost work. The problem is that parent is visible in children:

In [3]: parent = MenuItem.objects.create(title='Parent')
In [4]: child1 = MenuItem.objects.create(title='First child')
In [5]: child2 = MenuItem.objects.create(title='Second child')

In [6]: parent.children.all()
Out[6]: <QuerySet []>

In [7]: child1.children.all()
Out[7]: <QuerySet []>

In [9]: parent.children.add(child1)
In [10]: parent.children.add(child2)

In [11]: parent.children.all()
Out[11]: <QuerySet [<MenuItem: First child>, <MenuItem: Second child>]>

In [12]: child1.children.all()
Out[12]: <QuerySet [<MenuItem: Parent>]>

In my understanding, Out[12] should still return Empty Queryset.

South migrations broken in >= 0.8.0

Hi there.

It seems like migrations using south (On django 1.6 in my case) broke with the 0.8.0 release, manually verified through bisecting, haven't gotten through to finding the exact commit.

Anyway, my migration looks something like:

def forwards(self, orm):
    ParentModel = orm.ParentModel
    for o in ParentModel.objects.all():
        o.sorted_m2m_field.add(o.old_field)

Running this migration gives:

    o.sorted_m2m_field.add(o.old_field)
  File "/opt/src/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 583, in add
    self._add_items(self.source_field_name, self.target_field_name, *objs)
  File "/opt/src/env/local/lib/python2.7/site-packages/sortedm2m/fields.py", line 226, in _add_items
    with atomic(using=db, savepoint=False):
  File "/opt/src/env/local/lib/python2.7/site-packages/django/db/transaction.py", line 251, in __enter__
    "The outermost 'atomic' block cannot use "
django.db.transaction.TransactionManagementError: The outermost 'atomic' block cannot use savepoint = False when autocommit is off.

I suppose this has something to do with incompatible changes between south and django1.7-style migrations, I will try to dig in a little further myself aswell.

widget.js adds sortedm2m class to too many ul's

Very useful app...

Using 0.4.0,myself, but appears to be the same in latest.

widget.js
7. $('.sortedm2m').parents('ul').each(function () {
I believe should be:
7. $('.sortedm2m').parents('ul:first').each(function () {

hits further parents if its in nested ul.

Probably does not affect many, but first parent really is what you are after in this case.

Unable to add multiple objects and drop/dragging feature not working

Hey!
I came across sortedm2m through photologue and I am very interested in using it, however it is not working as planned and I cannot come to figure it out why not. I intend on creating an application similar to photologue (and the example you give in your doc) with a gallery object that you can add multiple photo objects to. I am able to make a gallery object and have it point to a photo object, however when I select more than one photo object, it will only add the most recently checked object in the table of checkboxes for photos. No errors will be produced, on the contrary, there will be a success message indicating that the object was changed successfully.

Along with that, I am unable to drag & drop the photo objects in the list to actually sort them. When hovering over a photo object, the cursor turns in to the drag & drop icon but it only highlights the text, not moving any of them.

I figured maybe it was something I was doing wrong, but then I decided to build the example "testapp" that you provided in your repo, which is bare-boned like the way I am trying to utilize sortedm2m, and I still got the same result: ParkingArea object only allowing one Car object to be added and drag/drop feature not working (parallel to my Gallery and Photo object respectively). However, after looking at phologue's demo website that the developer provides, their admin page is able to successfully use sortedm2m the way it was intended.

Your documentation doesn't really explain if there is anything to modify in admin.py file so maybe I am missing some sort of necessary step there? I am out of ideas on my end, maybe you can help?

Here are the portions of my models that use sortedm2m:

#models.py
from sortedm2m.fields import SortedManyToManyField

 class ImageModel(models.Model): 

    image = ThumbnailerImageField(
        'image',
        max_length=100,
        upload_to='photos'
    )
    ...
    class Meta:
        abstract = True
    ...
 class Photo(ImageModel):

    title = models.CharField(
        'title',
        max_length=250,
        unique=True
    )
    ...
 class Gallery(models.Model):

    title = models.CharField(
        'title',
        max_length=250,
        unique=True
    )
    photos = SortedManyToManyField(
        Photo,
        related_name='gallery',
        verbose_name='photos',
        blank=True
    )
    ...

Let me know if there is any other information you would like me to provide about my app, however I tried to make it similar to the way it is projected in your example project.

Thanks!
Lucas

Unique over the three values

In my current project I have the problem that I want the unique index over the three columns (from_, to, field.sort_value_field_name) in generated through model which is currently specified fix: 53322c4a[…]/sortedm2m/fields.py#L74

What should I do in this case?

Should be there an option three_column_unique?

Using a "through" intermediate model

Hi,
I couldn't get sortedm2m to work when tried with an intermediate model. Without it works perfectly.

My code is like this:

class Photo(models.Model):
    file = models.ImageField()

class Gallery(models.Model):
    name = models.CharField(max_length=1000, default="")
    photos = SortedManyToManyField(Photo, through="PhotosToGalleries")

class PhotosToGalleries(models.Model):
    gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE)
    photo = models.ForeignKey(Photo, on_delete=models.CASCADE)
    featured = models.BooleanField()

All seems fine, but I see nothing in the admin panel, and when trying to run some_gallery_object.photos.all() I the following error:
AttributeError: type object 'PhotosToGalleries' has no attribute '_sort_field_name'

Does sortedm2m supports defining my own intermediate model?

I'm using Django 1.9.5 with Python 3.

Thanks

ProgrammingError or OperationalError?

Hi,

I'm using django-sortedm2m in a project that I maintain: django-photologue. I think that I've found a bug related to django 1.7 migrations.

Django-photologue comes with its own Example Project (under folder /example_project/).
If I check out photologue, then setup this example project as per the README, in the
following environment:

  • Python 3.3
  • Django 1.7c2

By default the Example Project uses SQLite3 as a database; when I run the migrations,
the database is set up normally.

If I then edit settings.py to use Postgres as a database, and run the migrations for this
new database, I get the following error:

(photologue-3.3-1.7c2)vagrant@test2:~/projects/photologue/django-photologue/example_project$ ./manage.py migrate photologue 
Operations to perform:
  Apply all migrations: photologue
Running migrations:
  Applying photologue.0001_initial...Traceback (most recent call last):
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "photologue_gallery_photos" does not exist
LINE 1: SELECT COUNT(*) FROM "photologue_gallery_photos"
                             ^


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "./manage.py", line 14, in <module>
    execute_from_command_line(sys.argv)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/core/management/base.py", line 337, in execute
    output = self.handle(*args, **options)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/core/management/commands/migrate.py", line 160, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/migrations/executor.py", line 63, in migrate
    self.apply_migration(migration, fake=fake)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/migrations/executor.py", line 97, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/migrations/migration.py", line 107, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/migrations/operations/fields.py", line 37, in database_forwards
    field,
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/backends/schema.py", line 395, in add_field
    return self.create_model(field.rel.through)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/backends/schema.py", line 208, in create_model
    definition, extra_params = self.column_sql(model, field)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/backends/schema.py", line 120, in column_sql
    default_value = self.effective_default(field)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/backends/schema.py", line 170, in effective_default
    default = field.get_default()
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/models/fields/__init__.py", line 719, in get_default
    return self.default()
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/utils/functional.py", line 17, in _curried
    return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs))
  File "/home/vagrant/projects/photologue/django-sortedm2m/sortedm2m/fields.py", line 98, in default_sort_value
    return model._default_manager.count()
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/models/manager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/models/query.py", line 338, in count
    return self.query.get_count(using=self.db)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/models/sql/query.py", line 424, in get_count
    number = obj.get_aggregation(using=using)[None]
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/models/sql/query.py", line 390, in get_aggregation
    result = query.get_compiler(using).execute_sql(SINGLE)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/models/sql/compiler.py", line 785, in execute_sql
    cursor.execute(sql, params)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/backends/utils.py", line 81, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/utils/six.py", line 549, in reraise
    raise value.with_traceback(tb)
  File "/home/vagrant/.virtualenvs/photologue-3.3-1.7c2/lib/python3.3/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "photologue_gallery_photos" does not exist
LINE 1: SELECT COUNT(*) FROM "photologue_gallery_photos"
                             ^
(photologue-3.3-1.7c2)vagrant@test2:~/projects/photologue/django-photologue/example_project$

The error is coming from sorted-m2m fields.py, line 98 - it's set up to trap OperationalError exceptions, but a ProgrammingError is raised instead.

Please let me know if I can supply any more relevant information.

How to get queryset in sorted order?

I'm using DRF to expose my data via a REST API, and just realized I'm not serving it in the order it has been arranged in via the Django admin interface. What is the correct method for building the queryset in sorted order?

queryset = GalleryPage.objects.all()

Performance - browser freezes with 14k+ items

We have tested sortedm2m with the Django 1.6.6 and Mezzanine 3.1.9 having 14000+ items in the m2m.

The admin page in Chrome starts to allocate too much memory 1,5+ GB then it is killed by browser.

Checkbox not displayed when using jet dashboard

When used with jet dashboard (http://jet.geex-arts.com/),
checkbox are not displayed in admin. This prevents user to select fields.

Correction proposal for templates/sortedm2m/sorted_checkbox_select_multiple_widget.html:

11c11
<         <li><label{{ row.label_for|safe }}>{{ row.rendered_cb }} {{ row.option_label }}</label></li>

---
>         <li>{{ row.rendered_cb }} <label{{ row.label_for|safe }}>{{ row.option_label }}</label></li>
15c15
<         <li><label{{ row.label_for|safe }}>{{ row.rendered_cb }} {{ row.option_label }}</label></li>

---
>         <li>{{ row.rendered_cb }} <label{{ row.label_for|safe }}>{{ row.option_label }}</label></li

This way, it works. Did not see any drawback.

Migrations are broken in Django 1.7.4

I've just upgraded from Django 1.7.1 to Django 1.7.4 straight. There was one issue in the Django project (check https://code.djangoproject.com/ticket/24104) which was making some other app to break when running migrations with SQLite at least (typically used in tests).

I tried to run the tests in Django 1.7.3 and django-sortedm2m fields were fine, so it can very well be related with that issue. Hopefully this is enough to address the problem quickly.

Here is the traceback:

Running migrations:

  Applying a.0001_initial... OK

  Applying b.0001_initial... OK

  (...)

  Applying c.0001_initial... OK

  Applying c.0002_auto_20141110_1027...Traceback (most recent call last):

  File "manage.py", line 9, in <module>

    execute_from_command_line(sys.argv)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line

    utility.execute()

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute

    self.fetch_command(subcommand).run_from_argv(self.argv)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 50, in run_from_argv

    super(Command, self).run_from_argv(argv)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv

    self.execute(*args, **options.__dict__)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 71, in execute

    super(Command, self).execute(*args, **options)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute

    output = self.handle(*args, **options)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 88, in handle

    failures = test_runner.run_tests(test_labels)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/test/runner.py", line 147, in run_tests

    old_config = self.setup_databases()

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/test/runner.py", line 109, in setup_databases

    return setup_databases(self.verbosity, self.interactive, **kwargs)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/test/runner.py", line 299, in setup_databases

    serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/backends/creation.py", line 377, in create_test_db

    test_flush=True,

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 115, in call_command

    return klass.execute(*args, **defaults)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute

    output = self.handle(*args, **options)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 161, in handle

    executor.migrate(targets, plan, fake=options.get("fake", False))

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 68, in migrate

    self.apply_migration(migration, fake=fake)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 102, in apply_migration

    migration.apply(project_state, schema_editor)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 108, in apply

    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 37, in database_forwards

    field,

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 176, in add_field

    self._remake_table(model, create_fields=[field])

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 144, in _remake_table

    self.quote_name(model._meta.db_table),

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/backends/schema.py", line 102, in execute

    cursor.execute(sql, params)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute

    return self.cursor.execute(sql, params)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute

    return self.cursor.execute(sql, params)

  File "/home/user/virtualenv/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 485, in execute

    return Database.Cursor.execute(self, query, params)

django.db.utils.OperationalError: table shop_shop__new has no column named shop_actions

shop_actions is a sortedm2m field and is the only type of field breaking.

Support for Django 1.7

Django 1.7 will be released "soon" - in one week or one month, who knows! - and is feature-frozen, so we can start testing 3rd party applications against it.

It introduces a new database schema migration system, in replacement of South. This will mean quite a few changes for sortedm2m.

An interesting blog on supporting the new migrations system: http://treyhunner.com/2014/03/migrating-to-django-1-dot-7/

Background:

I'm the maintainer of django-photologue, which depends on sortedm2m, and when I run Photologue's unit tests against Django 1.7 I get several errors such as:

======================================================================
ERROR: test_previous_gallery_mismatch (photologue.tests.test_photo.PreviousNextTest)
Photo does not belong to the gallery.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/vagrant/projects/photologue/django-photologue/example_project/../photologue/tests/test_photo.py", line 116, in setUp
    self.test_gallery.photos.add(self.pl1)
  File "/home/vagrant/.virtualenvs/photologue-2.7-1.7b/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 915, in add
    self._add_items(self.source_field_name, self.target_field_name, *objs)
  File "/home/vagrant/.virtualenvs/photologue-2.7-1.7b/local/lib/python2.7/site-packages/sortedm2m/fields.py", line 163, in _add_items
    source_field_name: self._fk_val,
  File "/home/vagrant/.virtualenvs/photologue-2.7-1.7b/local/lib/python2.7/site-packages/model_utils/managers.py", line 245, in __getattr__
    return getattr(self.get_queryset(), name)
AttributeError: 'PhotoQuerySet' object has no attribute '_fk_val'

My initial impression is that sortedm2m was relying on some internal (hidden) variable within Django in order to work, and that this non-public API has been changed.

At the moment I'm looking into other upgrade issues with Photologue. If/when I finish with these I might also be able to take a closer look at sortedm2m.

Using TEMPLATES setting does not work with django-mobile

I received this bugreport by email:

I'm trying to get django-mobile working with a clean install of Wagtail CMS (https://wagtail.io/)

I made separate mobile templates and followed the install instructions but it doesn't work out of the box and I'm wondering if you had any tips?

To get it to work at all actually I had to change in the settings from:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(PROJECT_DIR, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

to this:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(PROJECT_DIR, 'templates'),
        ],
        #'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django_mobile.context_processors.flavour',
            ],
            'loaders': [
                # insert your TEMPLATE_LOADERS here
                ##'django_mobile.loader.CachedLoader',
                'django_mobile.loader.Loader',
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
        },
    },
]

commenting out the APP_DIRS to make loaders work. While this didn't seem to break wagtail as long as I add the app_directories.Loader, django-mobile still isn't working :(

Migrate problem

Before applying it, edit the migration file and change in the operations list migrations.AlterField to AlterSortedManyToManyField (import it from sortedm2m.operations). This operation will take care of changing the intermediate tables, add the ordering field and fill in default values.

After this and migrate.

Applying shop.0032_auto_20150617_2132...Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Volumes/WDC/Documents/Development/Web/rifktk-virtualenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Volumes/WDC/Documents/Development/Web/rifktk-virtualenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Volumes/WDC/Documents/Development/Web/rifktk-virtualenv/lib/python3.4/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Volumes/WDC/Documents/Development/Web/rifktk-virtualenv/lib/python3.4/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "/Volumes/WDC/Documents/Development/Web/rifktk-virtualenv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 221, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/Volumes/WDC/Documents/Development/Web/rifktk-virtualenv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 110, in migrate
    self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
  File "/Volumes/WDC/Documents/Development/Web/rifktk-virtualenv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 147, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Volumes/WDC/Documents/Development/Web/rifktk-virtualenv/lib/python3.4/site-packages/django/db/migrations/migration.py", line 115, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/Volumes/WDC/Documents/Development/Web/rifktk-virtualenv/lib/python3.4/site-packages/sortedm2m/operations.py", line 12, in database_forwards
    to_model = to_state.render().get_model(app_label, self.model_name)
AttributeError: 'ProjectState' object has no attribute 'render'

django 1.8, python3. thanks.

Deprecation warnings on Django 1.10

After updating to Django 1.10, I'm seeing a deprecation warnings which originate from django-sortedm2m:

...
/Users/<username>/.virtualenvs/<proj>/lib/python3.5/site-packages/sortedm2m/fields.py:334: RemovedInDjango20Warning: Usage of ForeignObjectRel.to attribute has been deprecated. Use the model attribute instead.
  to_model = self.rel.to
/Users/<username>/.virtualenvs/<proj>/lib/python3.5/site-packages/sortedm2m/fields.py:354: RemovedInDjango20Warning: Usage of field.rel has been deprecated. Use field.remote_field instead.
  if self.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to_object_name == klass._meta.object_name:
/Users/<username>/.virtualenvs/<proj>/lib/python3.5/site-packages/sortedm2m/fields.py:354: RemovedInDjango20Warning: Usage of ForeignObjectRel.to attribute has been deprecated. Use the model attribute instead.
  if self.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to_object_name == klass._meta.object_name:
/Users/<username>/.virtualenvs/<proj>/lib/python3.5/site-packages/sortedm2m/compat.py:37: RemovedInDjango20Warning: Usage of field.rel has been deprecated. Use field.remote_field instead.
  db_constraint=field.rel.db_constraint)
/Users/<username>/.virtualenvs/<proj>/lib/python3.5/site-packages/sortedm2m/fields.py:360: RemovedInDjango20Warning: on_delete will be a required arg for ForeignKey in Django 2.0. Set it to models.CASCADE on models and in existing migrations if you want to maintain the current default behavior. See https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.on_delete
  **get_foreignkey_field_kwargs(self))
...

Most of these look fairly minor, but it just might be slightly annoying to make the changes work across older versions of Django.

RemovedInDjango19Warning

When adding a related item (in my example a choice to a multiplechoice question:

>>> q.choices.add(c)
/home/jorick/.virtualenvs/allianz/lib/python3.4/site-packages/sortedm2m/fields.py:88: RemovedInDjango19Warning: django.db.models.get_model is deprecated.
  model = models.get_model(klass._meta.app_label, name)

Problem with AlterSortedManyToManyField or the documentation about it

Hi, so I just found django-sortedm2m and am stoked about it, but I ran into a little problem integrating it. The problem is a little similar to #60 so hopefully I'll shed a little light on what might be going on

I have an two existing models with a many-to-many relationship with a custom through-table. That table already has an 'order' field. As such, as per the Readme on github, I used the sort_value_field_name. I also followed the Readme and modified the created migration to use AlterSortedManyToManyField.

The problem is that AlterSortedManyToManyField does not take into account a custom sort value field name. It only uses the default: operations.py:77

For my situation, the solution was simple. Just don't use the operation and everything else else just works great! But I think maybe either the operation should take into account a sort_value_field_name set on the field or, more simply, the documentation should just highlight that if you have an existing field and through table, don't change the migration.

Thanks the package

EDIT: oh, I also had to add _sort_field_name = 'order' to my through model, so maybe it should be addressed in AlterSortedManyToManyField

Widget not diplaying properly in forms.

Hey, I am quite new to Django and was trying to implement the sortedm2m widget in my forms. The code I used is

class TrackForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the track title.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
genres = SortedMultipleChoiceField(queryset=Genre.objects.all())

but I got this. It is plain list of labels without the scroller, also multiple objects cannot be added only one of the selected object is added to the Trackform data. I am thinking, it may be due failing widget.

screenshot from 2016-07-10 15 54 48

False child relation with SortedMany2ManyField('self')

I created a model with a SortedMany2ManyField to itself named children.
I created 4 Treks, test1, test2, test3 and test4 with no children.
I opened test1 in admin, selected test2, test3, test4 as children, and saved it.

Now, if I open test2, test3 or test4, I see test1 as a child...
It only appends when the SortedMany2ManyField link 'self'

capture du 2015-09-16 14 49 14
on the picture, 3 first are expected, 3 last are unexpected

Name of order field in migrations

Problem IMHO in migrations of Django 1.7 (not South). I use custom field name for order field in M2M:

attributes = SortedManyToManyField(Attribute, sort_value_field_name='order')

then make migration and apply it. After which in db was created M2M table with default field name ('sort_value') instead my overriding name ('order').

TypeError: Error when calling the metaclass bases

Using South for migrations I get a TypeError when initializing:

./manage.py schemamigration myapp --initial

TypeError: Error when calling the metaclass bases
type() argument 1 must be string, not unicode

class Photo(models.Model):
    name = models.CharField(max_length=50)
    image = models.ImageField(upload_to='...')

class Gallery(models.Model):
    name = models.CharField(max_length=50)
    photos = SortedManyToManyField(Photo)

[django 1.7 + postgres] Migrations doesn't seem to work

As a minimal example, I created foo app with Photo and Gallery models. Here's models.py:

from django.db import models
from sortedm2m.fields import SortedManyToManyField


class Photo(models.Model):
    name = models.CharField(max_length=50)


class Gallery(models.Model):
    name = models.CharField(max_length=50)
    photos = SortedManyToManyField(Photo)

Then, i've run manage.py makemigrations foo, which created 0001_initial.py:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import sortedm2m.fields


class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Gallery',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=50)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Photo',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=50)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='gallery',
            name='photos',
            field=sortedm2m.fields.SortedManyToManyField(to='foo.Photo', help_text=None),
            preserve_default=True,
        ),
    ]

When I run manage.py migrate foo, I get a PostgreSQL error:

psycopg2.ProgrammingError: ERROR:  relation "foo_gallery_photos" does not exist
LINE 1: SELECT COUNT(*) FROM "foo_gallery_photos"

Can you reproduce this error? If so, this is a critical issue, django 1.7 is already released as stable.

sort_value_field_name is not recognized / Django 1.8.1

Hi,

I don't get the option sort_value_field_name persited to migrations and adding manually also does not recognize it.

model:

nodes = SortedManyToManyField(Node, sort_value_field_name='order')

migration:

migrations.AddField(
    model_name='location',
    name='nodes',
    field=sortedm2m.fields.SortedManyToManyField(to='campus.Node', help_text=None, sort_value_field_name='order'),
),

I got lost in the process of "Rendering model states…" I think.

I run ./manage.py migrate in pycharm with debugging and break point in my subclass implementing the new hook of #49.
The function called three times. First run perfect (I think this is registering in the app), second and third run shows attrs['_sort_field_name'] = 'sort_value' in the calling stack of rendering state in the migration?!

Silent failure when adding duplicate items

Adding a duplicate of the same model instance to a SortedManyToMany relationship silently fails.

Intuitively, I can understand how unordered Django ManyToMany fields behave as a Set and do not allow duplicates. But for an ordered relationship, I would expect it to behave like a List, and dropping duplicates is counterintuitive.

Are there any known workarounds, or do you know of any other tools better suited for implementing list/queue/stack behavior where duplicates are allowed?

# models.py

from django.db import models
from sortedm2m.fields import SortedManyToManyField

class Task(models.Model):
    name = models.CharField(max_length=255)

class Routine(models.Model):
    tasks = SortedManyToManyField('Task')
# usage:
sleep = Task(name='sleep')
sleep.save()

eat = Task(name='eat')
eat.save()

work =Task(name='work')
work.save()

routine = Routine()
routine.save()

 routine.tasks.add(eat)   # 1
 routine.tasks.add(work) # 2
 routine.tasks.add(eat)    # 3 = duplicate of 1
 routine.tasks.add(sleep) # 4

 routine.tasks.count() # returns 3

Access to sort_value column value

Greetings, I am trying to use sorted to order some questions inside a quiz, so far I have these two models:

class Quiz(models.Models):
    text = models.CharField(max_length=255)
    questions = SortedManyToManyField("Question")

class Question(models.Model):
    text = models.CharField(max_length=255)
    .
    .
    .

In my views I need to get the sorted_value column value but its not accessible. Question object has not sorted_value property. I used to have a property called "order", I removed but the migration created kept the field. But when I reorder questions inside admin, the value which is changed is sort_value. I need to access this sort_value.

how to update the order of m2m

I know from the doc that we can keep the order as we added. For example

class Photo(models.Model):
    name = models.CharField(max_length=100)


class Gallery(models.Model):
    name = models.CharField(max_length=100, default='gallery')
    photos = SortedManyToManyField(Photo)


p1 = Photo.objects.create(name='photo 1')
p2 = Photo.objects.create(name='photo 2')
p3 = Photo.objects.create(name='photo 3')

gallery = Gallery.objects.create(name='gallery')
gallery.photos.add(p1)
gallery.photos.add(p2)
gallery.photos.add(p3)

so photos in gallery keep in order [p1, p2, p3]. But how can I update this order, is there a convenient way provided?

sorry it maybe a simple question, but I didn't figure out.

Django 1.9 support

Just took 1.9b1 for a spin, and immediately get this trying to start my app using SortedManyToManyField

File ".../sortedm2m/fields.py", line 8, in <module>
    from django.db.models.fields.related import add_lazy_relation, create_many_related_manager

Looks like create_many_related_manager has been removed, but I can't find explicit reference to this in the release notes.

Admin inlines

If inline form contains sortedm2m field, drag-n-drop won't worked when I click "Add another inline form". How I can re-init this functionality? Also, I cannot change ordering of selected items without uncheking one of them, changing ordering and checking again.

Not quite compatible with django-cms placeholders outside of the cms

All this is on Django 1.4.2, django-cms 2.3.3, sortedm2m 0.5.0

I have a model that has 3 SortedManyToManyField and several PlaceholderFields (see: http://django-cms.readthedocs.org/en/2.3.3/extending_cms/placeholders.html#placeholders-outside-the-cms)

I am using fieldsets in Admin and it seems that if block that contains my sortedm2m's comes before all of the placeholder fieldset blocks (each can contain only a single Placeholder), then, jquery.ui.sortable throws a number of errors, beginning with:

Uncaught TypeError: Cannot read property 'constructor' of undefined jquery.ui.sortable.js:467
$.widget.$.extend._connectWith jquery.ui.sortable.js:467
$.widget.$.extend._refreshItems jquery.ui.sortable.js:525
$.widget.$.extend.refresh jquery.ui.sortable.js:461
$.widget.$.extend._init jquery.ui.sortable.js:23
$.Widget._createWidget jquery-ui.js:360
$.(anonymous function).(anonymous function) jquery-ui.js:263
(anonymous function) jquery-ui.js:323
jQuery.extend.each jquery.js:580
jQuery.fn.jQuery.each jquery.js:245
$.fn.(anonymous function) jquery-ui.js:315
(anonymous function) widget.js:24
jQuery.extend.each jquery.js:580
jQuery.fn.jQuery.each jquery.js:245
(anonymous function) widget.js:7
jQuery.extend.ready jquery.js:392
DOMContentLoaded jquery.js:745

Oddly, if at least one of the Placeholder blocks comes before the block containing the sortedm2m's, it all happily co-exists. I've tried changing up which ones come first, etc., and the only thing that helps, is when there is at least one of the placeholder blocks first.

If it helps, here's what my fieldsets definition looks like:

class MyModelAdmin(Placeholder):

    ...  # other options

    fieldsets = (
        (None, {
            'fields': (
                ('name', 'slug', ),
                ('start_date', 'end_date', 'location', ),
                ('seat_price', 'num_seats', ),
                'published',
            ),
        }),
        # This is broken like this. it MUST follow at least ONE of the placeholder groups.
        ('Speakers, Sponsors, Learn Options', {
            'classes': ['collapse'],
            'fields': (
                'speakers',  # This is a sortedm2m
                'sponsors',  # This is a sortedm2m
                'learn_options',  # This is a sortedm2m
            ),
        }),
        ('Detail Page Content', {
            'classes': ['plugin-holder', 'plugin-holder-nopage'],
            'fields': (
                'description_ph',   # This is a Placeholder
            ),
        }),
        ...  # More placeholder blocks
    )

Also, I tried removing the 'collapse' class from my sortedm2m's fieldset, it seems to make no difference either way.

IntegrityError when migrating model

Perhaps I am missing something very obvious, but after migrating an existing m2m to a sorted m2m I get an IntegrityError (development setup, so using sqlite)

django.db.utils.IntegrityError: NOT NULL constraint failed: manager_set_exercises__new.sort_value

Shouldn't make_sort_by_field in operations.py add a sort field with a default?

field = models.IntegerField(name=SORT_VALUE_FIELD_NAME, default=1)

Running the test suite?

Tried:

$ python runtest.py

But got:

RuntimeError: App registry isn't ready yet.

Am am I just missing the obvious? how to run the suite?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.