An warware: django admin auto update filin kwanan wata

Babban matsalar ita ce filin sabunta kwanan wata ta atomatik ba a sarrafa shi da kyau daga Django. Idan kayi ฦ™oฦ™arin sabunta filin kwanan wata ta amfani da dubawar mai gudanarwa, Django zai sabunta duk filayen da ke cikin tebur ta atomatik tare da suna iri ษ—aya, gami da filin kwanan sabunta ta atomatik. Wannan na iya haifar da canje-canje na bazata da yuwuwar kuskure ga bayananku.

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>

Menene filin sabunta atomatik

Filin "Sabuntawa ta atomatik" filin boolean ne a cikin tebur "saituna" na aikin Django. Lokacin da aka saita zuwa Gaskiya, Django zai bincika sabuntawa ta atomatik zuwa fayilolin saitunan aikin kuma, idan an sami sabon saiti, zai sabunta fayilolin saitunan aikin.

Shafi posts:

Leave a Comment