Same start and end date in DateRangePicker using plotly dash - plotly-dash

I have used daterangepicker in my application.
There is a situation where is need to select start_date and end_date as same dates, so that I can view sales details on that particular day.
By default dateRangePicker makes me to select at least two days(ie 20/04/2020 - 21/04/2020) but I would like it to be (20/04/2020 - 20/04/2020) .
Id there any way to achieve this ?

Yes but it must be done programatically. It depends on your specific implementation but you can create a callback to update the date picker range end_date when start_date is updated:
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dbc.Container(children=[
dcc.DatePickerRange(
id="date-range-picker")
])
#app.callback(Output("date-range-picker", "end_date"),
[Input("date-range-picker", "start_date")])
def update_start_date(start_date):
return start_date
app.run_server(debug=True)
Or you could simply set both via another callback say when a report button was clicked

In your DatePickerRange definition, pass minimum_nights=0 , and then you should be able to select same dates.
dcc.DatePickerRange(
id='dates',
display_format="DD-MM-YY",
start_date = date.today(),
end_date = date.today(),
minimum_nights=0
)

Related

Get available rooms in selected dates django

I am creating a project similar to a house booking system, with a few particularities (you publish the house but you can rent the rooms individually, and you can set when you are on holidays and the house is not available) in Django (rest-framework, so only API for now). The house model can be simplified to:
class House(models.Model):
title = models.CharField(max_length=127)
n_rooms = models.PositiveSmallIntegerField()
there is a calendar to save when the house is not available:
class Unavailability(models.Model):
house = models.ForeignKey(House, on_delete=models.CASCADE, related_name="house_unavailability")
unavailable_rooms = models.SmallIntegerField()
from_date = models.DateField()
to_date = models.DateField()
and a model to save when there have been bookings:
class Booking(models.Model):
house = models.ForeignKey(House, on_delete=models.CASCADE, related_name='booking')
booker = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
start_date = models.DateField()
end_date = models.DateField()
n_rooms = models.PositiveSmallIntegerField(default=1)
rent = models.DecimalField(decimal_places=2, max_digits=8)
I am now trying to create an API to search the houses that have at least one room available in the selected dates (not on holidays and not booked).
I have seen some similar cases without the particularities I have and using other languages but none using Django (I am using MySQL so I could fall back to SQL if a clean solution with Django does not arise)
Here, I am try to write a query that will provide expected result but I am not tested that query so may syntax error will be there but I think it will help.
from django.db.models import Sum, Value, IntegerField, Q, F
from django.db.models.functions import Coalesce
from django.utils import timezone
given_start_date = timezone.now().date() # assuming
given_end_date = timezone.now().date() # assuming
houses_at_least_one_room_available = House.objects.annotate(
total_unavailable_rooms=Coalesce(
Sum("house_unavailability__unavailable_rooms", filter=Q(
house_unavailability__from_date__range=(given_start_date, given_end_date),
house_unavailability__to_date__range=(given_start_date, given_end_date)
), distinct=True),
Value(0),
output_field=IntegerField()
),
total_booked_rooms=Coalesce(
Sum("booking__n_rooms", filter=Q(
booking__start_date__range=(given_start_date, given_end_date),
booking__end_date__range=(given_start_date, given_end_date)
), distinct=True),
Value(0),
output_field=IntegerField()
),
available_rooms=F("n_rooms") - F("total_unavailable_rooms") - F("total_booked_rooms")
).filter(available_rooms__gt=0)
Here, you can update the filter query inside Sum according to your use case.

Python - MySql.Connector UPDATE statement not working

I am having some problems with my UPDATE statement with MySQL.Connector.
My code apparently works sometimes and others not, and I don't understand why.
I made a test function, for one row, which is very similar to my other main function.
import mysql.connector
from datetime import datetime
def connect():
return mysql.connector.connect(host="xxxxx.xxx", user="xxx", passwd="xxxxxx", db="xxx")
def test():
mydb = connect()
mycursor = mydb.cursor()
sql = "SELECT MAX(value) FROM test"
mycursor.execute(sql)
date = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
for x in mycursor.fetchall():
updateSql = "UPDATE test SET date=%s WHERE value=%s"
vals = (date, x[0])
mycursor.execute(updateSql, vals)
mydb.commit()
print(vals)
print(mycursor.rowcount)
test()
This code doesn't seem to be working, as the printed rowCount value is 0.
My vals are correctly displayed : ('12-01-2020 16:47:15', 'testValue')
However, what is shown on the database is : '00-00-0000 00:00:00' .
Any ideas on how to solve this?
Edit: just found the answer.
I was using the wrong formatting.
date = datetime.now().strftime("%d-%m-%Y %H:%M:%S") wasn't properly recognized.
The DATETIME type in mySql databases requires the format to be the following:
date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with the Year in the first place, Month in the second one, and Day in the third one.
If this standard isn't followed then the date will be converted into 0000:00:00 00:00:00 .

How to Override "ir.sequence" field in csv import in Odoo?

I'm trying to import new customer data into Odoo using CSV import. There is one field customer_id_no which is auto generated when the record is created(using the "ir.sequence").
Now each customer record in the CSV has a unique customer_id_no but when I try to import it, the existing customer_id_no is overridden by the standard sequence.
How can I insert the data from CSV as it is in the Odoo?
Also I was unable to find an answer to import many2one fields. Any help on that would be greatful.
#CZoellner is right. You have to change your method. It would be something like this :
#api.model
def create(self, vals):
vals['customer_id_no'] = mechanics_to_generate_sequence()
return super(ClassName, self).create(vals)
It needs to address the case where customer_id_no is provided. Like this
#api.model
def create(self, vals):
if not vals.get('customer_id_no'):
vals['customer_id_no'] = mechanics_to_generate_sequence()
return super(ClassName, self).create(vals)
Note that afterward you would need to make the sequence next iteration to the value next to the highest in customer_id_no.

Convert CSV column format from string to datetime

Python 3.4 ... I am trying to convert a specific column in CSV from string to datetime and write it to the file. I am able to read and convert it, but need help writing the date format change to the file (the last line of code - needs to be modified). I got the following error for last line of code Error: sequence expected.
import csv
import datetime
with open ('/path/test.date.conversion.csv') as csvfile:
readablefile = csv.reader(csvfile)
writablefile = csv.writer(csvfile)
for row in readablefile:
date_format = datetime.datetime.strptime(row[13], '%m/%d/%Y')
writablefile.writerow(date_format)
So date_format is an instance of the datetime class. You need to format a string to print out to file. You can go with the standard:
date_format.isoformat()
Or customize your own format:
date_format.strftime('%Y-%m-%d %H:%M:%S')
Also a couple more things to note. You can't write to the same file you're reading from like that. If you want to overwrite that file, create a tmp file then replace it when done, but it's better to just create another file. The best solution imho is to make good use of stdin and stdout like this:
import csv
import sys
from datetime import datetime
FIELD = 13
FMT = '%m/%d/%Y'
readablefile = csv.reader(sys.stdin)
writablefile = csv.writer(sys.stdout)
for row in readablefile:
dt = datetime.strptime(row[FIELD], FMT)
row[FIELD] = dt.isoformat()
writablefile.writerow(row)
Now you can call the script like so:
cat /path/test.date.conversion.csv | python fixdate.py > another_file.csv
At this point, you can make use of the argparse module to provide all kinds of nice parameters to your script like:
Which field to format?
What input and/or output format?
etc.

How to use Django ORM to function on a field

This question is a follow-up to this one.
I'm running a Django application on top of a MySQL (actually MariaDB) database.
My Django Model looks like this:
from django.db import models
from django.db.models import Count, Sum
class myModel(models.Model):
my_string = models.CharField(max_length=32,)
my_date = models.DateTimeField()
#staticmethod
def get_stats():
logger.info(myModel.objects.values('my_string').annotate(
count=Count("my_string"),
sum1=Sum('my_date'),
sum2=Sum(# WHAT GOES HERE?? #),
)
)
When I call get_stats, it gives me the count and the sum1.
However, for sum2, I want the sum of the following Database expression for each matching row: my_date + 0 (this converts it to a true integer value).
What should I put in the expression above to get that sum returned in sum2?
When I change it to sum2=Sum(F('my_date')), I get the following exception: http://gist.github.com/saqib-zmi/50bf572a972bae5d2871
Not sure, but try F() expression
from datetime import timedelta
myModel.objects.annotate(
count=Count("my_string"),
sum1=Sum('my_date'),
sum2=Sum(F('my_date') + timedelta(days=1))
).values('my_string', 'count', 'sum1', 'sum2')
https://docs.djangoproject.com/en/dev/ref/models/queries/#f-expressions