Reputation: 1270
I am building a Blog WebApp and I am trying to implement a Feature.
What i am trying to do :-
I am trying to display the Date or Time of user's signup
(Like stack overflow does (member since 2 months))
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
full_name = models.CharField(max_length=100,default='')
time = models.DateTimeField(auto_now_add=True)
@property
def age(self):
current_datetime = datetime.now(tz=datetime.timezone.utc)
return (current_datetime - self.time).days
template.html
{{ request.user.profile.time }}
Upvotes: 1
Views: 83
Reputation: 997
You can use property
in models. By using this you will be able to fetch age
everytime you query Profile
model
from datetime import datetime, timezone
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, default='', unique=True)
full_name = models.CharField(max_length=100, default='')
time = models.DateTimeField(auto_now_add=True)
@property
def age(self):
current_datetime = datetime.now()
#current_datetime = datetime.now(timezone.utc) for tz aware datetimes
return (current_datetime - self.time).days
Upvotes: 1
Reputation: 21
You could use django-model-utils
. To be more specific create model that inherit TimeStampedModel
.
To render "since " you could use django.contrib.humanize.templatetags.humanize
.
To use directly in code:
humanize.naturaltime(datetime.datetime.now() - yourmodelinstance.created)
To use in template:
{% load humanize %}
{{ yourmodelinstance.created | naturaltime }}
Your example would look like:
import datetime
from django.contrib.humanize.templatetags import humanize
from model_utils.models import TimeStampedModel
class Profile(TimeStampedModel):
user = models.OneToOneField(User, on_delete=models.CASCADE, default='', unique=True)
full_name = models.CharField(max_length=100, default='')
@property
def age(self):
return humanize.naturaltime(datetime.datetime.now() - self.created)
To get rid of alot of milisecond You could replace age property return value with:
@property
def age(self):
return humanize.naturaltime(datetime.datetime.now().replace(microsecond=0) - self.created.replace(microsecond=0)
Upvotes: 1