Home > database >  How to make Django admin update the file name
How to make Django admin update the file name

Time:06-14

My django server uses file creation date as the file name in admin side. The files are added by software as well as by user. In the latter case my django server always uses the timestamp of the server start. How can I change it to use the time stamp of the file creation ?

enter image description here

admin.py

from django.contrib import admin
from .models import SyncScriptLog
from django.core.management import call_command


class SyncScriptLogAdmin(admin.ModelAdmin):
    actions = ['make_sync']

    def make_sync(self, request, queryset):
        call_command('update_rdf_from_api', "90", int(request.POST['_selected_action']))
        messages.add_message(
            request, messages.INFO, 'Amazing synchronization from multiple API sources to RDF TripleStore is DONE!')
    make_sync.short_description = "Run Sync from API to RDF"
    make_sync.acts_on_all = True

admin.site.register(SyncScriptLog, SyncScriptLogAdmin)

models.py

from django.db import models
from datetime import datetime

class SyncScriptLog(models.Model):
    title = models.CharField(max_length=20, default=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), editable=False)
    content = models.TextField()

    def __str__(self):
        return self.title

CodePudding user response:

You should not set default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), since that will evaluate the expression when it interprets the file for the first time, and then keeps using that value as default.

You can pass a callable to the default=… parameter [Django-doc], and let that return a value, so:

from django.db import models
from django.utils.timezone import now

def generate_title():
    return now().strftime('%Y-%m-%d %H:%M:%S')

class SyncScriptLog(models.Model):
    title = models.CharField(max_length=20, default=generate_title, editable=False)
    # …
  • Related