Solved: django admin auto update date field

The main problem is that the auto update date field is not properly handled by Django. If you try to update the date field using the admin interface, Django will automatically update all of the fields in the table with the same name, including the auto update date field. This can lead to unexpected and potentially incorrect changes to your data.


I have a model with a date field. I want to automatically update the date field when an object is created or edited in the admin panel. How can I do this?


A:

You can override <code>save_model</code> method of your admin class and set the value of <code>date</code> field to <code>datetime.now()</code>. 
<blockquote>
<p><strong><a href="https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin" rel="nofollow noreferrer">ModelAdmin</a></strong></p>
<p><strong><a href="https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django-contrib-admin-options-modeladmin-save_model" rel="nofollow noreferrer">save_model()</a></strong></p>
<p>[...] This method should save the object and return the new instance.</p>
</blockquote>
Example: 
<code>class MyModelAdmin(admin, ModelAdmin):

    def save_model(self, request, obj, form, change):

        if not change: # obj is being created for first time (i e., it's new)

            obj = super().save_model(request, obj, form, change) # create object first

            # now set your custom values here... 

            obj = super().save_model(request, obj, form=form._meta['fields'], change=change) # update object with custom values    

        else: # existing object is being edited (i e., it's not new)    

            # now set your custom values here... 

            obj = super().save_model(request, obj=obj._meta['fields'], form=form._meta['fields'], change=change) # update object with custom values        

        return obj  
</code>

What is Auto update field

The “Auto update” field is a boolean field in the “settings” table of a Django project. When set to True, Django will automatically check for updates to the project’s settings files and, if any new settings are found, will update the project’s settings files.

Related posts:

Leave a Comment