Format DateTime in Django Admin

Posted: March 10th, 2010 | Author: Arif Harbott | Filed under: Django | Tags: , | 6 Comments »

If you are trying to format a DateTimeField() field in the Django admin you may find it harder than you think. You would think that the DATE_FORMAT and DATETIME_FORMAT in settings.py would apply to the admin BUT it only applies to date formatting in the template.

At present there is no easy way to format the date but the following example of one method of how to do it:

class News(models.Model):
    headline = models.CharField(max_length=100)
    date = models.DateTimeField()
    article = models.TextField()
    published = models.BooleanField()

class NewsAdmin(admin.ModelAdmin):
    list_display = ('headline', 'format_date', 'published')

    def format_date(self, obj):
        return obj.date.strftime('%d %b %Y %H:%M')
    format_date.short_description = 'Date'

object instance / type / typeof

Posted: March 10th, 2010 | Author: Davo | Filed under: Django | Tags: , , , | 1 Comment »

In some circumstances it is useful to know what type() / instance the object is.
Python provides 2 useful built in functions which can be handy for this kind of operations.

>>> from apps.deals.models import Deal
>>> deal = Deal.objects.get(id=1)
>>> type(deal).__name__ # retrieve the name of the class
'Deal'
>>> type(Deal()).__name__ # same
'Deal'
>>> type(str()).__name__ # internal python string class.
'str'

Now lets see how the isinstance() works

>>> isinstance(deal, str) # is 'deal' instance of 'str' ?
False
>>> isinstance(deal, Deal) # is 'deal' instance of Deal ?
True
>>>