djangodjango-modelsdjango-admin

Prefill a DateTimeField from URL in django admin


How to prefill a DateTimeField from URL in django admin?

Let's say your model is :

class MyModel(models.Model):
    name = models.CharField(max_length=14)
    date = models.DateTimeField()

Then you can have the model "Add" form prefilled with values by passing them as GET parameters to the add view like:

/admin/app/mymodel/add/?name=Test

This is a really cool feature but how do you achieve this for a DateTimeField?

I tried many possible formats without success.

Update:

It seems impossible to do because django admin uses a SplitDateTimeWidget for DateTimeField. But if you don't mind using a different widget and loosing the datepicker, you can use a DateTimeInput widget instead.

The fastest way is to add this to your ModelAdmin class:

formfield_overrides = {
    models.DateTimeField: {'widget': DateTimeInput},
}

Solution

  • First define the serialization/deserialization format:

    DATETIME_FORMAT="%Y-%m-%d %H:%M:%S"  
    

    Then when you want to open the admin url use it:

    copiedArguments = {
       "fromDateTime": event.fromDateTime.strftime(DATETIME_FORMAT)
    }
    return HttpResponseRedirect(
                u"{}?{}".format(reverse('admin:events_event_add'), urllib.urlencode(copiedArguments)))
    

    last but not least extract the datetime in the model admin:

    def get_changeform_initial_data(self, request):
        initialData = super(EventAdmin, self).get_changeform_initial_data(request)
        initialData["fromDateTime"] = datetime.datetime.strptime(request.GET["fromDateTime"],DATETIME_FORMAT)
        return initialData