Django, actual month in queryset - django

how ill, get my register based in the current (actual) month in my queryset?, i have a ModelManager(), that just show the LIVE register status, but now i want to show the register with LIVE status and in the current (actual) month, i know that ill make something like .filter(...), but i dont know how get the current month..
model.py
#manager
class LiveNoticiaManager(models.Manager):
def get_query_set(self):
return super(LiveNoticiaManager,self).get_query_set().filter(status=self.model.LIVE_STATUS)
thanks guys.

http://docs.djangoproject.com/en/dev/ref/models/querysets/#month
You can
>>> import datetime
>>> today = datetime.date.today()
>>> MyModel.objects.filter(mydatefield__year=today.year,
mydatefield__month=today.month)

That's if you are only interested in gettting the month:
import datetime
today = datetime.date.today()
months = ['zero','January','February','March','April','May','June','July','August','September','October','November','December']
current_month = months[today.month]

Related

Calcul Time on django

I have the following code:
def index(request):
events_list = Timesheet.objects.filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]).order_by('-working_hour')
total_hours_week = Timesheet.objects.annotate(total_hours_per_week=Sum('working_hour')).filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1])
return render(request, "timesheet/index.html", {'events_list': events_list, 'total_hours_week': total_hours_week})
the total_hours_week retun the current error:
You cannot use Sum, Avg, StdDev, and Variance aggregations on date/time fields in sqlite3 since date/time is saved as text.
Do you know how to fix ?
thanks per advance
You can check if the current DB engine is sqlite3 or not, and calculate annotations programmatically in case that is needed:
from django.conf import settings
def index(request):
db_engine = settings.DATABASES['default']['ENGINE']
if db_engine = 'django.db.backends.sqlite3':
total_hours_week = [] # Calculate annotation programmatically
else:
total_hours_week = Timesheet.objects.annotate(total_hours_per_week=Sum('working_hour')).filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1])
events_list = Timesheet.objects.filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]).order_by('-working_hour')
return render(request, "timesheet/index.html", {'events_list': events_list, 'total_hours_week': total_hours_week})
However, if you are using sqlite3 only for development, and you need to work with time aggregations a lot, I strongly recommend you to setup a PostgreSQL/MySql server for your development environment, as it saves you a lot of time and headache in long run.

How to make previous day's date and today's date only accessible in date time picker in Odoo?

I am trying to check on a condition where the today's date is only accessible to get selected in the date time picker in Odoo and the code is as follows.
def onchange_date(self, cr, uid, ids, fdate, context=None):
if fdate:
if datetime.strptime(fdate, "%Y-%m-%d %H:%M:%S").date() <>
datetime.now().date():
return { 'value': { 'fdate': False } }
return fdate
I also wanted to make the previous day i.e yesterday's date to be available to the user to get selected along with today's date.
selected_date = datetime.strptime(fdate, "%Y-%m-%d %H:%M:%S").date()
yes_date = datetime.strptime(fdate, "%Y-%m-%d %H:%M:%S").relativedelta(days = -1).date()
today = datetime.now().date()
if selected_date <> today and selected_date <> yes_date
And add the import file for relative delte
If you only use Dates, you should use date instead of datetime, and if first if you only want a user use the date of today, get automatically the date of today and put it readonly, something like this:
...
import time
...
#here you got a field with the date of today.
date_today = fields.Date('Today is: ', default = lambda *a: time.strftime("%Y-%m-%d"), readonly = True)
And if you want what one user only be able to choose the days yesterday and today, it's a little bit more laborious, I know this is not the best way to do it but it work fine.
...
from openerp.exceptions import ValidationError
...
chosen_date = fields.Date('Chosen day: ', default = lambda *a: time.strftime("%Y-%m-%d"))
#api.onchange('chosen_date'):
def _onchange_chosen_date(self):
yesterday = str( int(time.strftime("%d")) - 1 )
if len(yesterday) == 1:
yesterday = '0' + yesterday
yesterday_date = time.strftime("%Y-%m-" + yesterday)
if self.chosen_date != time.strftime("%Y-%m-%d") or self.chosen_date != yesterday_date:
return { 'warning': {'title':"Warning", 'message':"You are only able to choose only yesterday and today...!"}}
EDIT
I only use V8, but I know something of V7 syntax!
1th.
...
import time
...
#here you got a field with the date of today.
date_today = fields.date('Today is: ', default = lambda *a: time.strftime("%Y-%m-%d"), readonly = True)
2th.
...
from openerp.osv import osv
...
chosen_date = fields.date('Chosen day: ', default = lambda *a: time.strftime("%Y-%m-%d"))
def _onchange_chosen_date(self, cr, uid, ids, chosen_date, context=None):
yesterday = str( int(time.strftime("%d")) - 1 )
if len(yesterday) == 1:
yesterday = '0' + yesterday
yesterday_date = time.strftime("%Y-%m-" + yesterday)
if self.chosen_date != time.strftime("%Y-%m-%d") or self.chosen_date != yesterday_date:
raise osv.except_osv(("Warning"),("You are only able to choose only yesterday and today...!"))
And in the XML:
<field name="chosen_date" on_change="_onchange_chosen_date(chosen_date)" />
I hope this can be helpful for you!!!

'None type' object has no attribute 'year'

I'm trying to get the year from a datetime form but I'm getting this error when I run the project code 'None type' object has no attribute 'year' I've tried both import datetime and from datetime import datetime but with no success. Although in another function placed before this one in the same file views.py I wrote the same code (of year getting...) and it works very well!
PS: when I run the code on the ipdb shell it works correctly!
this the code:
from datetime import datetime
def My_function(request):
data = tableA.find()
dt = datetime.now()
y = dt.year
m = dt.month
d = dt.day
for i in data:
if i['ma_date'].year == y:
ma_liste.append([i["ma_date"])
return render(request, ma_page.html, ma_liste)
and this is the erreor
**AttributeError at /ma_page/
'NoneType' object has no attribute 'year'**
This has nothing to do with datetime. Your data item has no year attribute.
You haven't shown your code or a structure for this object, but it's likely it's just a multidimensional array, in which case you could use: i['ma_date']['year'].

Date value loaded once with Django QuerySet filtered on date.today

Scenario: a queryset filtered by a date value seems to use a date value as generated by the process once and then reused for all subsequent requests. That is, if the app is running for a few days, and a piece of content is published with the publish date equal to the current day, it will not show up as published until the application server is reloaded.
The obvious answer is that the queryset is using date.today() instead of date.today, however that's not the case here:
from datetime import date, timedelta
from django.db import models
class PublishedManager(models.Manager):
def get_query_set(self):
return super(PublishedManager, self).get_query_set().filter(
published_date__lte=date.today, active=True)
Why is date.today not being evaluated properly? Am I missing something blindingly obvious here or is there something else going on?
This is an app running Django 1.4.16 on Python 2.7 with Apache mod_wsgi.
You need to call the method:
date.today()
date.today just returns the built-in method. It doesn't actually call it. Example:
>>> from datetime import date
>>> date.today
<built-in method today of type object at 0x97f780>
>>> date.today()
datetime.date(2014, 11, 4)

selectdatewidget set default month and day

How can I set selectDateWidget day and month options to default as 1st January but leave the year option intact.
Now I am doing:
day = datetime.date.today()
lessTime = forms.DateField(required=False, widget=SelectDateWidget(years=range(1980, 2013)), initial=day)
But this sets the default to the actual date. What can I change to give me the desired default options?
Thanks in advance
Make a custom widget e.g MySelectDateWidget
class MySelectDateWidget(SelectDateWidget):
def render(self, name, value, attrs=None):
from collections import namedtuple
date_tweak = namedtuple('Date', 'year month day')
date_value = date_tweak(None, 1, 1) #tweak to cheat SelectDateWidget's
#render method which expects a datetime object
return super(MySelectDateWidget, self).render(name, date_value, attrs)
and then replace:
lessTime = forms.DateField(required=False,
widget=SelectDateWidget(years=range(1980, 2013)), initial=day)
with:
lessTime = forms.DateField(required=False,
widget=MySelectDateWidget(years=range(1980, 2013)))