Atrisināts: django admin automātiskās atjaunināšanas datuma lauks

Galvenā problēma ir tā, ka Django nepareizi apstrādā automātiskās atjaunināšanas datuma lauku. Ja mēģināt atjaunināt datuma lauku, izmantojot administratora saskarni, Django automātiski atjauninās visus tabulas laukus ar tādu pašu nosaukumu, tostarp automātiskās atjaunināšanas datuma lauku. Tas var izraisīt neparedzētas un potenciāli nepareizas izmaiņas jūsu datos.

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>

Kas ir automātiskās atjaunināšanas lauks

Lauks “Automātiskā atjaunināšana” ir Būla lauks Django projekta “iestatījumu” tabulā. Ja tas ir iestatīts uz True, Django automātiski pārbaudīs projekta iestatījumu failu atjauninājumus un, ja tiks atrasti jauni iestatījumi, atjauninās projekta iestatījumu failus.

Related posts:

Leave a Comment