selectdatewidget set default month and day - django

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)))

Related

Dynamic search using date

Can any one please help me i want to search my expenses income which is in my models.py using date wise dynamic search where user will input date and he will see the result in template i dont know how to code that template ..I tried form but not working.. :(
my views.py
def date_page(request):
f_date = '2018-12-05'
t_date = '2019-09-12'
from_date = datetime.datetime.strptime(f_date, "%Y-%m-%d").date()
to_date = datetime.datetime.strptime(t_date, "%Y-%m-%d").date()
date_queryset = Add.objects.filter(date__range=(from_date, to_date))
print (date_queryset)
return render (request , 'date_page.html',)
Pass the date value as URL parameter and fetch it using request.GET as,
def date_page(request):
f_date = request.GET.get("f_date")
t_date = request.GET.get("t_date")
date_queryset = Add.objects.filter(date__range=(f_date, t_date))
print(date_queryset)
return render(request, 'date_page.html', )
Example URL : /api/end-point/expenses/?f_date=2018-12-05&t_date=2019-09-12

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!!!

Flask-Admin customize datetime view

When using flask-admin, the list view for datetime fields is something like this: "2014-02-22 13:30:43".
I'd like to know if is possible to change this default view for something like this: "2014-02-22" or "2014-02-22 13:30".
thanks
Yes, you can set the column_type_formatters to define default formats. Also, you can set column_formatters to use custom formats only to one column in your list view.
https://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.column_formatters
https://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.column_type_formatters
from flask_admin.model import typefmt
from datetime import date
def date_format(view, value):
return value.strftime('%Y-%m-%d')
MY_DEFAULT_FORMATTERS = dict(typefmt.BASE_FORMATTERS)
MY_DEFAULT_FORMATTERS.update({
date: date_format
})
form_args = dict(
time = dict(validators=[DataRequired()],format='%Y-%m-%d %H:%M')
)
form_widget_args = dict(
time={'data-date-format': u'YYYY-MM-DD HH:mm'}
)
column_type_formatters = MY_DEFAULT_FORMATTERS
This will change the date format to 2014-02-22 13:30.

Django, calendar

I need to use a calendar. I'm developing a website for house's rental, my first own web project, so, the idea is that the user selects an initial date and finish date, in the same month or any months (from January until April for example), and in the view (template) of the housing availability.
I want to show all months (12) and where is busy the house I'll show the days with some different color.
I'm searching and testing for Django calendar, but if somebody knows about it, please give me a hand :)
Thanks :)
Did you take a look at Django Schedule and Django SwingTime ?
Take a look at some of the calendar related exapmles here to see if they work for you:
http://www.djangosnippets.org/tags/calendar/
Also, you might consider using Python's HTMLCalendar as discussed here:
Creating a Flexible Monthly Calendar in Django
Here it is an example of overiding HTMLCalendar to display a queryset:
class QuerysetCalendar(HTMLCalendar):
def __init__(self, queryset, field):
self.field = field
super(QuerysetCalendar, self).__init__()
self.queryset_by_date = self.group_by_day(queryset)
def formatday(self, day, weekday):
if day != 0:
cssclass = self.cssclasses[weekday]
if date.today() == date(self.year, self.month, day):
cssclass += ' today'
if day in self.queryset_by_date:
cssclass += ' filled'
body = ['<ul>']
for item in self.queryset_by_date[day]:
body.append('<li>')
body.append('<a href="%s">' % item.get_absolute_url())
body.append(esc(item))
body.append('</a></li>')
body.append('</ul>')
return self.day_cell(cssclass, '%d %s' % (day, ''.join(body)))
return self.day_cell(cssclass, day)
return self.day_cell('noday', ' ')
def formatmonth(self, year, month):
self.year, self.month = year, month
return super(QuerysetCalendar, self).formatmonth(year, month)
def group_by_day(self, queryset):
field = lambda item: getattr(item, self.field).day
return dict(
[(day, list(items)) for day, items in groupby(queryset, field)]
)
def day_cell(self, cssclass, body):
return '<td class="%s">%s</td>' % (cssclass, body)

Django, actual month in queryset

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]