check if today is due date django - django

I have a model like this
class Tasks(models.Model):
title = models.CharField(max_length=100,null=True,blank=True)
due_date_time= models.DateTimeField(default=timezone.now)
As due date is a date and time field, how I can check if today is due date of this task , while I am saving time and date both

You can make use of the __date lookup [Django-doc]:
from django.utils.timezone import now
Tasks.objects.filter(
due_date_time__date=now().date()
)
or if you work with timezones, you can work with a range check:
from datetime import timedelta
from django.utils.timezone import now
today = now().replace(hour=0, minute=0, second=0, microsecond=0)
tomorrow = today + timedelta(days=1)
Tasks.objects.filter(
due_date_time__gte=today,
due_date_time__lt=tomorrow
)
Note: normally a Django model is given a singular name, so Task instead of Tasks.

Related

how to set default hour for my django datetimefield

im trying to set default hour to my django datetimefield , im using datetime-local in my input , but it shows current time , i want to set default time to 12:00 PM and changeable as well
i tried this but doesnt work
from datetime import datetime
def set_default_time_checkout():
now = datetime.now()
new_time = now.replace(hour=12, minute=0, second=0, microsecond=0)
return new_time
class Booking(models.Model):
check_in = models.DateTimeField(default=timezone.now)
check_out = models.DateTimeField(default=set_default_time_checkout,blank=True,null=True)
but doesnt work
and this is my forms.py
class BookingForm(forms.ModelForm):
check_in = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'}))
check_out = forms.DateTimeField(initial=set_default_time_checkout, required=False,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'}))
also the initial time doesnt work in the modelform is it possible please ? how to achieve it ? i tried these solutions from the question but none of them works
Can I set a specific default time for a Django datetime field?
thanks in advance
This might probably work:
import datetime
defualt=datetime.time(12, 0, 0)
The output of datetime.time() has hour, minute and second instances

Django / PostGreSQL: Create queryset grouped by 'date' when each row has a different timezone

Let's say I have two models:
from django.db import model
class Company(model.Model):
name = models.TextField()
timezone = models.TextField()
class Sale(models.Model):
amount = models.IntegerField()
company = models.ForeignKey('Company')
time = models.DateTimeField()
I want to create a queryset grouped by date and company, where date refers to the calendar date of the sale at the timezone specified on the Company object.
This query:
result = Sale.objects.values(
'company', 'time__date'
).aggregate(
models.Sum('amount')
)
This returns the data in a format that works for me. However, the sales are grouped by UTC day. I want them grouped by the timezone on the Company objects.
What is the cleanest, quickest way to do this?
I know I could dump the entire set of values into Python, like this:
result = Sale.objects.values(
'amount', 'company__timezone', 'time'
).order_by(
'company_timezone'
)
for r in result:
r.date = r.time.astimezone(pytz.timezone(r.company_timezone)).date()
and then groupby, but is there a better way?
The solution is to use the TruncDate function, and pass the timezone string as an argument.
from django.db.models.functions import TruncDate
from django.db.models import F
...
local_time_daily_sales = Sale.objects.annotate(
date=TruncDate(tzinfo=F('company__timezone'))
).values(
date
).annotate(Sum('amount'))

How can I find total number of signups in a week?

I am using django build in User model have one-to-one relation with UserProfile model. I have to count number of signups in a week. How can I do this?. Thanks in advance for your addition.
you can use date_joined in User model, it mean A datetime designating when the account was created. Is set to the current date/time by default when the account is created.
from datetime import datetime, timedelta
today = datetime.date.today()
startDate = today - datetime.timedelta(days=7)
endDate = today + datetime.timedelta(days=1)
users = User.objects.filter(date_joined__range=[startDate, endDate])

Django: Filter data based on expiration date coming within next 1 week and 2 weeks

I have a model class:
class Products(models.Model):
product = models.Charfield( field specs here . )
expiration_date = modelsDateTimeField ( . field specs here . )
Now I want the users to be able to see all the products which will expire in 1 week or/and 1 month or/and 3 months from today.
I have already tried:
from django_filters import rest_framework as filters
expiration_date_after = filters.DateFilter(field_name='expiration_date', lookup_expr='gte')
expiration_date_before = filters.DateFilter(field_name='expiration_date', lookup_expr='lte')
with this, I have to pass two parameters in the url:
/products/?expiration_date_after=2019-06-06&expiration_date_before=2019-06-12
But I want to pass in the url only 1 or 2 or 3 which will display data for 1 week, 2 weeks and 3 weeks .
So if i pass products/1 . it should filters expiration date for next 1 week.
and if i pass products/2 . it should filter expiration date for next 1 month.
I am new to django.... So please let me know what is best approach to this problem.
You should write query like this:
products = Products.objects.filter(expiration_date__range=[start_date, end_date])
if You want on weekley basis than you should do like this:
days = 7*n
start_date = today()
end_date = start_date + datetime.timedelta(days=days)
where n=number of weeks
Note: Do not forget to change date string to datetime object
I implemented this in this manner:
In custom_filters folder:
from Django_filters import rest_framework as filters
from date time import date time, date, timedelta
import datetime
class DaysFromTodayFilter(filters.Filter):
def filter(self,qs,value):
if value not in (None,''):
days_key = int(value):
today = datetime.date.today()
if days_key ==1:
x_days_from_today = today + date time.timedelta(days=7)
elif days_key ==2:
x_days_from_today = today + date time.timedelta(days=14)
return qs.filter(**{'%s__%s'%(self.field_name, 'range'):(today, x_days_from_today)})
return qs
In views.py file:
from Django_filters import rest_framework as filters
from views import DaysFromTodayFilter
from models import Products
import Django_filters
class ProductsFilter(Django_filters.FilterSet):
expiration_date_within = DaysFromTodayFilter(field_name='expiration_date')
It's working fine....
in the url:
localhost:8000/products/1
is filter all products which will expire in 1 week and /2 for two weeks

How to write the right time to DB according my timezone?

When I save dates in my database Django shows message about succesfull adding with the right time but in fact in the databese time is different
models.py:
from datetime import datetime
from django.db import models
class Teg1(models.Model):
created_at = models.DateTimeField(default=datetime.now, null=True, blank=True, editable=False)
num = models.FloatField(default=0.0, null=True, blank=True)
def __str__(self):
return str(self.num) + " || " + str(self.created_at)
settings.py
TIME_ZONE = 'Asia/Novosibirsk'
USE_TZ = True
The first sentence of Django's time zone documentation explains what you're seeing:
When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.
So the database value is in UTC. The str() value is also in UTC, since you've manually converted the UTC datetime to a string without changing the timezone. The value interpreted by the form and displayed by the template is in your local time, since templates convert DateTimeFields to the current timezone.
If you want the str() value to use the local timezone you can use Django's localtime() function:
from django.utils.timezone import localtime
class Teg1(models.Model):
...
def __str__(self):
return str(self.num) + " || " + str(localtime(self.created_at))
If i'm not mistaken, you must be in Russia which is 7 hours ahead of UTC. So, the server that you use must be using the UTC time which in my opinion is a good thing.
I personally prefer to save times in UTC time in the data base and then convert them to the local time in the front end.
from django.utils import timezone
from datetime import datetime
teg1 = Teg1(created_at=datetime.now(tz=timezone.utc)
teg1.save()
However, if you want to save the datetime in your local time, you can use:
from datetime import datetime
import pytz
novosibirsk = pytz.timezone("Asia/Novosibirsk")
now = datetime.now(novosibirsk)
teg1 = Teg1(created_at=now)
teg1.save()
Have in mind that in your admin interface, you might see the time and date based on the timezone you select in your settings.py. However, the data saved in the database is still in UTC time.
instead of using
from datetime import datetime
class Teg1(models.Model):
created_at = models.DateTimeField(default=datetime.now)
use (this will use timezone that you have set in settings.py)
from django.utils import timezone
class Teg1(models.Model):
created_at = models.DateTimeField(default=timezone.localtime())