Giter VIP home page Giter VIP logo

wagtail-orderable's People

Contributors

brianxu20 avatar djdmorrison avatar dylanncordel avatar elton2048 avatar garybutton avatar mjpieters avatar nickmoreton avatar peeterss avatar rddesmond avatar solarissmoke avatar th3hamm0r avatar tomdyson 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

Watchers

 avatar  avatar  avatar  avatar

wagtail-orderable's Issues

new post above - reverse order

Hi, I need to sort (in wagtail administration) by sort_order but to sort from largest to smallest

if i add:
sort_order_field = 'sort_order'
contributions are sorted from smallest to largest (and the new contribution is at the bottom)

I need the sorting reversed, so that the new post is at the top...

sort_order_field = '-sort_order' not working

get_list_display should handle tuples

The default list_display value on a wagtail.contrib.modeladmin.options.ModelAdmin instance is a tuple:

list_display = ('__str__',)

but the wagtailoderable.modeladmin.mixins.OrderableMixin implementation tries to concatenate that value with a list:

def get_list_display(self, request):
"""Add `index_order` as the first column to results"""
list_display = super(OrderableMixin, self).get_list_display(request)
order_col_prepend = ['index_order']
return order_col_prepend + list_display

This results in a TypeError exception. The OrderableMixin implementation should really return a tuple too:

 def get_list_display(self, request): 
     """Add `index_order` as the first column to results""" 
     list_display = super(OrderableMixin, self).get_list_display(request) 
    return ('index_order', *list_display)

The above uses iterable unpacking (new in Python 3.5) to create a new tuple from the values in list_display, which can be any iterable (including a list or tuple).

TypeError when creating the first Orderable object

Great package, thanks a lot for this.

I have just discovered that when saving the first object to an otherwise empty table of Orderable objects, the following TypeError will be thrown:

TypeError at /admin/app/accessibility/create/
unsupported operand type(s) for +: 'NoneType' and 'int'

This is because the following queryset in the Orderable().save() method will return None when it is working with an empty queryset:

self.__class__.objects.aggregate(Max('sort_order'))['sort_order__max']

All that is needed to fix this is a fallback to 0 when the queryset is empty. This might be as simple as the following:

# models.py/Orderable
def save(self, *args, **kwargs):
    if self.pk is None:
        sort_order_max = self.__class__.objects.aggregate(Max('sort_order'))['sort_order__max'] or 0
        self.sort_order = sort_order_max + 1
    super().save(*args, **kwargs)

I'd be happy to put together a PR for this change.

TypeError when using Orderable on regular Django models.Model

I'm running into a TypeError concerning MRO when combining the Orderable Class with a regular Django Model (as shown in the readme).

[...]
File "/var/www/ska/wagtail_orderable_test/models.py", line 5, in <module>
    class YourModel(models.Model, Orderable):
  File "/var/www/ska/studioska/lib/python3.6/site-packages/django/db/models/base.py", line 94, in __new__
    new_class = super_new(cls, name, bases, new_attrs, **kwargs)
TypeError: Cannot create a consistent method resolution
order (MRO) for bases Model, Orderable

This is using the exact example as shown in the readme:

from django.db import models

from wagtailorderable.models import Orderable

class YourModel(models.Model, Orderable):
    title = models.CharField(max_length=200)

The example using the Page class from Wagtail does work. As far as I can gather (with somewhat limited knowledge concerning subclassing in Python) this error is concerning the concatenation of class-methods, although I'm not able to determine where exactly this problem originates.

It is quite possible this is user-error (as mentioned, I'm not a python expert).

For reference, I'm using Wagtail 2.4 (latest stable) with Django 2.1.8 (latest version indicated for Wagtail 2.4) and Python 3.6.7.

ModelAdmin deprecated

This project enables admin views generated with ModelAdmin to be enriched with darg & drop ordering, which is awesome.
However, with the release of Wagtail 5 ModelAdmin is discontinued and will only receive maintenance updates.

Snippets are to be used instead, but there is, of course, no sort ordering provided there.
So for ModelAdmin folks, this is a step backwards.

Are there any plans for this project to provide the functionality for Snippets? Or is it tightly scoped to ModelAdmin only?

Support for Django 4

Hi Elton

I've just upgraded a Wagtail app that uses this package to Django 4, and am getting this error:

from wagtailorderable.modeladmin.mixins import OrderableMixin
File "/usr/local/lib/python3.10/site-packages/wagtailorderable/modeladmin/mixins.py", line 1, in <module>
from django.conf.urls import url
ImportError: cannot import name 'url' from 'django.conf.urls' (/usr/local/lib/python3.10/site-packages/django/conf/urls/__init__.py)

This looks like a simple fix, swapping out url for re_path, any chance this could be updated and released?

https://stackoverflow.com/a/70319607

Thanks,

Russell.

Ordering does not work when overriding the META-class

I've been searching quite a while to figure out why some of my models worked while others didn't.
By working I mean that you can see the dragging widget.

Finally I figured out that this problem comes from overriding the META class:

This code does not work:

from wagtailorderable.models import Orderable

class MyModel(Orderable):

    # Some fields, panels etc here

    class META:
         verbose_name_plural = "My Models"

This code does work:

from wagtailorderable.models import Orderable

class MyModel(Orderable):

    # Some fields, panels etc here

    # No META field

Extending META (instead of overriding) does work though, so this is probably the best option if you want to set verbose names etc.:

This code does work as well:

from wagtailorderable.models import Orderable

class MyModel(Orderable):

    # Some fields, panels etc here

    class META(Orderable.META): # note the inheritance here
         verbose_name_plural = "My Models"

In general I'm not sure, if this is a bug, I'd rather say this is unexpected behavior.

Support for filters in ModelAdmin

Thank you for making this plugin, it's super useful!

I was looking to use filters in the ModelAdmin view, this is not supported. The problem is that the query parameter that is generated and used is the absolute position in the list (which would depend on what which remains after filtering).

A proposed PR is #12 . This passes the pk for object to move before (when moving up the list) or after (when moving down the list) and adjusts the sort_order based on that.

SyntaxError in get_list_display

Hello,

I've found SyntaxError in return statement which prevent django startup.

Last line in get_list_display method, in OrderableMixin class.

wagtailorderable/modeladmin/mixins.py

    def get_list_display(self, request):
        """Add `index_order` as the first column to results"""
        list_display = super().get_list_display(request)
        return = ('index_order', *list_display)

UnboundLocalError at /cms/home/venue/reorder/3/: local variable 'update_value' referenced before assignment

Some details, and debugging comments and solution questions at the bottom of the OP:

Packages

wagtail-orderable 1.1.0
wagtail 3.0.3
django 4.0.7

Full stack error

[08/Sep/2022 16:00:25] "GET /cms/home/venue/reorder/3/?after=2 HTTP/1.1" 500 74627
Internal Server Error: /cms/home/venue/reorder/3/
Traceback (most recent call last):
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/wagtail/admin/urls/__init__.py", line 161, in wrapper
    return view_func(request, *args, **kwargs)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/wagtail/admin/auth.py", line 182, in decorated_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.9/contextlib.py", line 79, in inner
    return func(*args, **kwds)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/wagtailorderable/modeladmin/mixins.py", line 196, in reorder_view
    qs.update(**{self.sort_order_field: update_value})
UnboundLocalError: local variable 'update_value' referenced before assignment
Internal Server Error: /cms/home/venue/reorder/3/
Traceback (most recent call last):
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/wagtail/admin/urls/__init__.py", line 161, in wrapper
    return view_func(request, *args, **kwargs)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/wagtail/admin/auth.py", line 182, in decorated_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.9/contextlib.py", line 79, in inner
    return func(*args, **kwds)
  File "/home/vscode/.local/share/virtualenvs/workspace-dqq3IVyd/lib/python3.9/site-packages/wagtailorderable/modeladmin/mixins.py", line 196, in reorder_view
    qs.update(**{self.sort_order_field: update_value})
UnboundLocalError: local variable 'update_value' referenced before assignment

Relevant code

if position < old_position:
if position == after_position:
position += 1
qs = qs.filter(**{'%s__lt' % self.sort_order_field: old_position,
'%s__gte' % self.sort_order_field: position})
update_value = F(self.sort_order_field) + 1
signal_kwargs.update({'from_order': position, 'to_position': old_position + 1})
elif position > old_position:
if position == before_position:
position -= 1
qs = qs.filter(**{'%s__gt' % self.sort_order_field: old_position,
'%s__lte' % self.sort_order_field: position})
update_value = F(self.sort_order_field) - 1
signal_kwargs.update({'from_order': old_position - 1, 'to_position': position})
# let's signal we will reorder some instances.
pre_reorder.send(**signal_kwargs)
# reorder all previous|next
qs.update(**{self.sort_order_field: update_value})

Debugging

Printing print(position, old_position) in the above code prints 0, 0.

Looking at my database, I see that the sort_order column for all Venue records is NULL, and this is why position and old_position and so on are defaulting to 0.

So my question is: how are we meant to initialise the database with an arbitrary sort order, so that the ordering function works?

Status of this project

Hello, I see that the latest commit is like 18 months ago. Is this project still supported? Can I run it with latest wagtail versions (2.14)?

TIA

Prepopulate sort_order for existing models/pages

Thanks for this package! It is working great once I solved the following hick-up.
If you add this package to an existing Wagtail site, sort_order will not be populated on already existing pages. Added to list_display in ModelAdmin, you can see that it stays "-" or "0". Only after adding new pages, these "0" change to "1" possibly. Even then all pages with sort_order "0" or "1" cannot be resorted.
A possible solution could be a lookup of all pages with an undefined sort_order and if existant than prepopulate them. You know better then me where to implement this check:

pages = SomePage.objects.live().order_by('sort_order') 
if pages.filter(sort_order__isnull=True).exists() or pages.filter(sort_order=0).exists():
    for i, page in enumerate(pages):
        page.sort_order = i
        page.save()

sorting over pagination

hi, how do I move an object between 2 pages (multiple item pagination)?

I have 120 objects on two pages, I need an object from the first page to be moved somewhere on the second page...

Error in README

Great app. Minor documentation issue. OrderableMixin should come before ModelAdmin, like:

class YourModelAdmin(OrderableMixin, ModelAdmin):
    model = YourModel

django.template.exceptions.TemplateDoesNotExist: modeladmin/aboutus/distinguishtestimonial/index.html,

I tried to implement this library to some models in my wagtail project and it throws this error. I tried inheriting the models from wagtailorderable.models.Orderable and registered a wagtail_hooks. It even shows a new menu for the registered model on the wagtail admin sidebar but throws the following error upon loading it. It could be a compatibility issue.

Wagtail version - 5.0.2
Django version - 4.2.2
Python Version - 3.11.4

TemplateDoesNotExist at /admin/aboutus/distinguishtestimonial/
modeladmin/aboutus/distinguishtestimonial/index.html, modeladmin/aboutus/index.html, modeladmin/index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/aboutus/distinguishtestimonial/
Django Version: 4.2.2
Exception Type: TemplateDoesNotExist
Exception Value:
modeladmin/aboutus/distinguishtestimonial/index.html, modeladmin/aboutus/index.html, modeladmin/index.html
Exception Location: C:\olenepal\env\Lib\site-packages\django\template\loader.py, line 47, in select_template
Raised during: wagtail.contrib.modeladmin.options.index_view
Python Executable: C:\olenepal\env\Scripts\python.exe
Python Version: 3.11.4
Python Path:
['C:\olenepal\olewebsite\src',
'C:\Users\OleNepal\AppData\Local\Programs\Python\Python311\python311.zip',
'C:\Users\OleNepal\AppData\Local\Programs\Python\Python311\DLLs',
'C:\Users\OleNepal\AppData\Local\Programs\Python\Python311\Lib',
'C:\Users\OleNepal\AppData\Local\Programs\Python\Python311',
'C:\olenepal\env',
'C:\olenepal\env\Lib\site-packages']
Server time: Mon, 11 Sep 2023 12:00:03 +0545

Issue with Duplicate Sort_Order Values

Thank you for this package!

I was testing further yesterday and noticed that there was an issue with duplicate sort_order ids (it gets weird). I created #16 to resolve it. This:

  • Adds a function to remove duplicate (the sort order is re if duplicates are found)
  • Fixes case that produced them (new items are added with MAX instead of COUNT, because deletes cause gaps)
  • Updates the UI to cancel the move and show an error if the ajax command doesn't return 200.
  • Handles sort_order with 0 correctly

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.