Opened 2 days ago

Last modified 2 days ago

#35906 closed Bug

SplitDateTime widget crashes while processing initials — at Initial Version

Reported by: Михаил Акопян Owned by:
Component: Forms Version: 5.1
Severity: Normal Keywords: SplitDateTimeWidget AdminSplitDateTime
Cc: Михаил Акопян Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have a model with DateTime field. I want to set initials for this field in django admin by using query params. For example:

# models.py

class MyModel(models.Model):
    created_at = models.DateTimeField()


# admin.py

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    pass

Trying to create new object of MyModel with initial for created)at field:
http://127.0.0.1:8000/admin/myapp/mymodel/add/?created_at=2024-10-10%2005%3A57%3A31

Admin sites crashes with 500 error. This happens because the method decompress of the SplitDateTimeWidget expects an object of datetime type, but it is passed the string instead.

Proposed fix:

    def decompress(self, value):
        if isinstance(value, str):
            try:
                value = datetime.fromisoformat(value)
            except ValueError:
                return [None, None]
        if value:
            value = to_current_timezone(value)
            return [value.date(), value.time()]
        return [None, None]

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top