Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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},
}
like image 987
bformet Avatar asked Oct 28 '25 05:10

bformet


1 Answers

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
like image 106
Papers.ch Avatar answered Oct 31 '25 10:10

Papers.ch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!