开发者

How can I have my DateTimeField filled in automatically for my admin entries?

开发者 https://www.devze.com 2023-01-18 07:54 出处:网络
I have a date_added field for my entries and it\'s frustrating clicking the date and time when filling these in. I want this to happen behind the scenes and I don\'t want these to even show up.

I have a date_added field for my entries and it's frustrating clicking the date and time when filling these in. I want this to happen behind the scenes and I don't want these to even show up.

I've googled around and tried searching SO but was unable to find a snippet of how this can be done when I save my form.

Here's the relevant bit from admin.py:

class BugForm( forms.ModelForm ):
    class Media:
    #js = ( 'http://static.arounds.org/wmd/wmd.js', )
    js = ( 'http://ajax.googleapis.com/ajax/libs/mootools/1.2.3/mootools-yui-compressed.js', 'http://static.arounds.org/js/moowmd.js', 'http://static.arounds.org/js/wmd-config.js' )
    css = {
        'all': ('http://static.arounds.org/css/wmd.css',)
    }

    class Meta:
    model = Bug

class BugAdmin( admin.ModelAdmin ):
    fields = ['name', 'slug', 'excerpt', 'summary开发者_如何学运维', 'date_added', 'poster', 'categories', 'status']
    prepopulated_fields = { 'slug' : ['name'] }
    form = BugForm

I'm aware that I'll have to probably specify exclude = ('date_added',) and define a def save() function, but I'm not sure of the specifics needed for this.


I want this to happen behind the scenes and I don't want these to even show up.

IMHO the best way to do this is edit the model and set auto_now_add=True for the date_added field. This assumes you have access to edit the model. You'd do something like:

class Bug(models.Model):
    ...
    date_added = models.DateTimeField(auto_now_add=True)

This will solve both your problems: it will fill in the date time automatically and will not show up in the Admin app. From the docs:

Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it's not just a default value that you can override.

I'd like to note that there is a complementary auto_now that you can use for tracking updates. Setting auto_now=True will be useful for date_updated fields if any.

0

精彩评论

暂无评论...
验证码 换一张
取 消