3

Online material (docs, code) for django's (postgres-specific) range fields is lacking. I tried overriding the widget for DateTimeRangeField, but can't get it to show 2 pretty date-time inputs using SplitDateTimeWidget (start datetime, end datetime) for my field. I have settled for overriding the type attribute and getting the following okayish output, without this, it's just plain type="text".

Current behaviour:

Current okayish behaviour

Expected behaviour: Following, but 2 of them.

enter image description here

My models.py

from django.db import models
from django.contrib.postgres.fields import DateTimeRangeField

class MyModel(models.Model):
    ...
    datetimerange = DateTimeRangeField()
    ...

My admin.py

from django import forms
from django.contrib import admin
from django.contrib.postgres.forms.ranges import RangeWidget, DateTimeRangeField


class MyModelAdminForm(forms.ModelForm):
    class Meta:
        model = models.MyModel
        fields = "__all__"
        widgets = {
            "datetimerange": RangeWidget(
                forms.SplitDateTimeWidget(
                    date_attrs={"type": "date"}, time_attrs={"type": "time"},
                ),
            )
        }


@admin.register(models.MyModel)
class MyModelAdmin(admin.ModelAdmin):
    form = MyModelAdminForm

I tried playing around with (inheriting from) the default field DateTimeRangeField but no luck there as well.

shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
  • Having the same issue, did you find a solution? I just get empty tags... – Özer Oct 21 '20 at 09:29
  • @ÖzerS. I ended up splitting the field into 2 datetimes for this and other reasons. But in any case the above would still work, albeit, without the nice-looking separate date & time fields for both from & to datetime. – shad0w_wa1k3r Oct 21 '20 at 15:08
  • 1
    Haha, I did exactly the same, good old start_date and end_date, it's so much easier. I really tried a lot, but the support for the DateTimeRangeField is just not there. I think you can achieve it with custom widgets etc., but in the end you will have more code than simple start/end. – Özer Oct 22 '20 at 16:29

0 Answers0