简体   繁体   中英

How convert epoch time integerfield to datetime field in django admin

I use django and for saving time I am using epoch time in an IntegerField so my model is like this:

class MyModel(models.Model):
    start_time = models.IntegerField()

and start_time in admin is like this:

start_time 整数字段

It's not a problem but it's hard to check and update field for a person so my question is how can I convert this IntegerField to DateTimeField in django admin without changing my model? I know I can represent this field as readonly field and convert epoch time to DateTime but how can i use django admin DateTime picker?

I found my answer hope it help someone else, it's work but maybe it's not the best answer.

I used an intermediate field because I couldn't change the real field so I create a form to have a DateTimeField:

from django import forms
from django.contrib.admin.widgets import AdminSplitDateTime


class MyModelAdminForm(forms.ModelForm):
    start_date_time = forms.SplitDateTimeField(widget=AdminSplitDateTime())

    class Meta:
        model = MyModel
        fields = '__all__'

then I add form to my admin:

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    form = MyModelAdminForm
    fields = ('start_date_time',)

for setting initial value of previous saved object in form:

def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)
    if obj:
        form.base_fields['start_date_time'].initial = datetime.datetime.fromtimestamp(obj.start_time)
    return form

the result is:

纪元日期时间字段

and last step is saving DateTimeField to IntegerField as epoch time:

def save_model(self, request, obj, form, change):
    obj.start_time = round(form.cleaned_data['start_date_time'].timestamp())
    obj.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM