wagtail-nest / wagtail-modeladmin

Add any model in your project to the Wagtail admin. Formerly wagtail.contrib.modeladmin.
Other
22 stars 8 forks source link

modeladmin assumes ordering values are strings, and so crashes on F expressions #29

Open Pomax opened 4 years ago

Pomax commented 4 years ago

Issue Summary

https://github.com/wagtail/wagtail/blob/165c5c0ce5138f35ba313aba54f5a40392e876cc/wagtail/contrib/modeladmin/views.py#L491 assumes that ordering values are strings, e.g.:

class Something(...):
  ...
  class Meta:
    ordering = [
      'props1',
      '-props2',
   ]

However, that's only one of the two officially supported formats for ordering, the other being F expressions, e.g:

from django.db.models import F

class Something(...):
  ...
  class Meta:
    ordering = [
      F('props1').asc(nulls_last=True),
      '-props2',
   ]

As such, using F expressions causes a hard crash:

Traceback (most recent call last):
  File ".../django/core/handlers/exception.py", line 34, in inner   
    response = get_response(request)
  File ".../django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File ".../django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
[...snip...]
  File ".../django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File ".../django/template/base.py", line 904, in render_annotated 
    return self.render(context)
  File ".../django/template/library.py", line 214, in render        
    _dict = self.func(*resolved_args, **resolved_kwargs)
  File ".../wagtail/contrib/modeladmin/templatetags/modeladmin_tags.py", line 86, in result_list
    headers = list(result_headers(view))
  File ".../django/contrib/admin/templatetags/admin_list.py", line 109, in result_headers
    ordering_field_columns = cl.get_ordering_field_columns()
  File ".../wagtail/contrib/modeladmin/views.py", line 463, in get_ordering_field_columns
    if field.startswith('-'):
AttributeError: 'OrderBy' object has no attribute 'startswith'

This presumably also affects https://github.com/wagtail/wagtail/blob/165c5c0ce5138f35ba313aba54f5a40392e876cc/wagtail/contrib/modeladmin/views.py#L456 etc.

Steps to Reproduce

  1. Add a Meta ordering to any class you like
  2. Add an F expression as one of the ordering terms
  3. Try to view that class in the admin interface

Technical details

TonisPiip commented 1 year ago

Was able to hack together a fix for this, ping me if it's needed and I can share the hack

Pomax commented 1 year ago

Just post it here? (or file a PR of course)