i make a reservation system, which has form validation,
This should check whether the the bus on that date is already booked or not,
but, unfortunately there still error on this code..
so here my code :
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields = '__all__'
tempReDate = date(1,1,1) # temp local variable
def clean_start(self):
start = self.cleaned_data['start']
# cheacking if date for this bus is free
res_all = Booking.objects.all()
for item in res_all:
if start >= item.start and start <= item.end and item.resourceId == self.instance.resourceId:
raise forms.ValidationError("This date already reserved by same bus, choose other date or other bus")
#set variable to send for next funtion: clean_EndDate
self.tempReDate = start
return start
def clean_end(self):
#check if EndDate is empty
if not self.data['end']:
#set numbers days of reservation 1 if no end date
self.instance.numOfDays = 1
return None
# if start date is empty
if self.tempReDate == date(1,1,1):
raise forms.ValidationError("Must Choose start date")
# if start date is not empty
else:
start = self.tempReDate
end = self.cleaned_data['end']
# cheackig start date is not lower than end date
if end < start:
raise forms.ValidationError("start date cannot be later than end date")
# cheackig if reservation is no longer than 14 days
if end > start+ timedelta(days=14):
raise forms.ValidationError("You can make a reservation for max 14 days")
# cheacking if reservation for this bus is free
res_all = Booking.objects.all().filter(resourceId=self.instance.resourceId)
for item in res_all:
#jesli w przedziale nowego zamowienia jest poczatek albo koniec innego to zajęte
if start <= item.start and item.start <= end or start <= item.end and item.end <= end:
raise forms.ValidationError("This date already reserved by same bus, choose other date or other bus")
# calculateing number days of reservation and save it
var = end - start
self.instance.numOfDays = var.days + 1
return start
And this code on views.py
views.py
def create_book(request):
booking_forms = BookingForm()
customer_forms = CustomerForm()
if request.method == 'POST':
booking_forms = BookingForm(request.POST)
customer_forms = CustomerForm(request.POST)
if customer_forms.is_valid() and booking_forms.is_valid():
nama_pelanggan = customer_forms.cleaned_data['nama_pelanggan']
no_hp = customer_forms.cleaned_data['no_hp']
# nmpl = request.POST['nama_pelanggan']
# nm_pl = {"nama_pelanggan": nmpl}
customer, _ = Customer.objects.get_or_create(no_hp=customer_forms.cleaned_data['no_hp'],
defaults={
'nama_pelanggan': customer_forms.cleaned_data['nama_pelanggan'],
'alamat_pelanggan': '',
'tipe': ''
},)
idbooking = booking_forms.cleaned_data['idbooking']
resourceId = booking_forms.cleaned_data['resourceId']
start = booking_forms.cleaned_data['start']
end = booking_forms.cleaned_data['end']
harga_jual = booking_forms.cleaned_data['harga_jual']
uang_jalan = booking_forms.cleaned_data['uang_jalan']
parkir_bensin = booking_forms.cleaned_data['parkir_bensin']
note = booking_forms.cleaned_data['note']
Booking.objects.create(
idbooking=idbooking,
resourceId=resourceId,
start=start,
end=end,
harga_jual=harga_jual,
uang_jalan=uang_jalan,
parkir_bensin=parkir_bensin,
note=note,
title=resourceId,
nm_pelanggan=nama_pelanggan,
backgroundColor='blue'
),
return redirect('booking-list')
else:
print(booking_forms.errors)
print(customer_forms.errors)
context = {
'cform': customer_forms,
'form': booking_forms,
}
return render(request, 'booking/create_book.html', context)
What error ?
The problem im facing now, when i make reservation use same bus on same date, the validation error message not showing, and program continue make booking which is make double booking and will make conflict
.
what is problem with this form validation ?
.
thanks
Related
I have a Project model with the following fields:
class Project(db.Document):
project_name = db.StringField(max_length=80, required=True)
description = db.StringField(max_length=160, required=True)
start_date = db.DateTimeField(required=True)
end_date = db.DateTimeField(required=True)
created = db.DateTimeField()
status = db.BooleanField(default=False)
releases = db.ListField(db.ReferenceField(Release))
and I am trying to create a route that shows all the active projects only whose status are set to true, and their end date has not being passed.
UPDATED
#app.route('/search/projects', methods=['GET'])
def search_projects_get():
try:
proj = Project.objects
if proj.status is True and proj.end_date < datetime.now():
return jsonify(proj)
except Exception as e:
errors.bad_request(repr(e))
Can someone please help me complete the logic in my route?
I have the following situation:
This is my views.py:
def home(request):
date = datetime.date.today()
start_week = date - datetime.timedelta(date.weekday() + 1)
end_week = start_week + datetime.timedelta(6)
week_tasks = Task.object.filter(owner=request.user, start_date__range=[start_week, end_week])
context = {}
context['week_tasks'] = week_tasks
return render(request, 'home.html', context)
This view check if the start_date (DateField) is inside the range of the current week. But I have another field on the database, end_date, and I want to check if any value of this range is on the current week.
Check the exemple:
Let's supose that the current week is the week of the day 17. With my current view, only the All Day Event and Conference belong to the week. I need to show that all these events belong to the week.
Obs.: I can't just check if start_date and end_date are in the week, because I have the situation of the Long Event, that starts before the week and ends after.
WORKING:
views.py:
def home(request):
date = datetime.date.today()
if date.isoweekday() == 7:
date = date + datetime.timedelta(1)
start_week = date - datetime.timedelta(date.isoweekday())
end_week = start_week + datetime.timedelta(6)
week_tasks = Task.object.filter(owner=request.user).exclude(end_date__lt=start_week).exclude(start_date__gt=end_week)
context = {}
context['week_tasks'] = week_tasks
return render(request, 'home.html', context)
week window is defined by: week_start, week_end
tasks are defined by: task_start, task_end
task has overlap with week if:
task_start < week_end and task_end >= week_start
This is my code in Python - Flask. Here I am entering data for a Theatre (Theatre table) and then fetching the respective id and then adding the screen to the respective theatre_id in the Screen table.
The problem is Theatre gets added to the database and I am able to fetch the id. The code for Screen doesn't seem to work (for loop does work if I comment out the session.screen add and commit statement)
And even the rollback doesn't happen if screen commit doesn't happen.
session_theatre = Session_theatre()
session_screen = Session_screen()
id = 1
if request.method == "POST":
if form.validate_on_submit():
name = str(form.name.data)
city = str(form.location.data)
address = str(form.address.data)
no_of_screen = int(form.total_no_screen.data)
if (name !="" and name!=" " and city != "" and city != " " and address != ""and address != " " and no_of_screen != None):
t = Theatre(name,city,address,1)
try:
session_theatre.add(t)
session_theatre.commit()
query = session_theatre.query(Theatre).filter_by(name=name,city =city).all()
for i in query :
id = i
for i in range (0,no_of_screen):
flash(id)
screen = Screen(str(i+1),1,20,1,20,id)
session_screen.add(screen)
session_screen.commit()
flash("Successfully added !!")
except :
session_screen.rollback()
session_theatre.rollback()
flash("Oops something went wrong !!")
finally:
session_screen.close()
session_theatre.close()
else :
flash("Please fill the input")
return render_template('admin/add_theatre.html',form = form)
Screen Model
class Screen(db.Model):
__tablename__ = "screens"
id = db.Column(db.Integer,primary_key=True)
screen_num = db.Column(db.String(1))
seat_row_start = db.Column(db.Integer)
seat_row_end = db.Column(db.Integer)
seat_col_start = db.Column(db.Integer)
seat_col_end = db.Column(db.Integer)
theatre_id = db.Column(db.Integer, db.ForeignKey('theatres.id'))
def __init__(self, screen_num,
seat_row_start,seat_row_end,seat_col_start,seat_col_end,theatre_id):
self.screen_num = screen_num
self.seat_row_start = seat_row_start
self.seat_row_end = seat_row_end
self.seat_col_start = seat_col_start
self.seat_col_end = seat_col_end
self.theatre_id = theatre_id
To get a list from the query for session_theatre you have to add all() at the end:
query = session_theatre.query(Theatre).filter_by(name=name,city =city).all()
The query returns a list of Theatre objects and you can access the id attribute of each Theatre object iterating over the list and accessing the attribute by its name:
for obj in query :
for i in range (0,no_of_screen):
flash(obj.id)
screen = Screen(i+1,1,20,1,20,obj.id)
session_screen.add(screen)
session_screen.commit()
So here's the code ...
import win32com.client, datetime
from datetime import timedelta
def checkTime():
date_filter_unformated = datetime.date.today() - timedelta(days=3)
date_filter = date_filter_unformated.strftime("%m/%d/%y %I:%M:%S")
current_message = all_messages.GetPrevious()
message_time = current_message.ReceivedTime
df_list = list(date_filter)
mt_list = list(str(message_time))
df_month, mt_month = int(''.join([df_list[0],df_list[1]])), int(''.join([mt_list[0],mt_list[1]]))
df_day, mt_day = int(''.join([df_list[3],df_list[4]])), int(''.join([mt_list[3],mt_list[4]]))
df_year, mt_year = int(''.join([df_list[6],df_list[7]])), int(''.join([mt_list[6],mt_list[7]]))
if mt_year < df_year:
return "Old"
elif mt_year == df_year:
if mt_month < df_month:
return "Old"
elif mt_month == df_month:
if mt_day < df_day:
return "Old"
else:
CurrentMessage(current_message)
return "Pass"
elif mt_month > df_month:
CurrentMessage(current_message)
return "Pass"
def CurrentMessage(cm):
print cm.Sender, cm.ReceivedTime
#
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. Can change that number to reference
# any other folder
all_messages = inbox.Items
current_message = all_messages.GetLast()
while True:
if checkTime() == "Pass":
continue
if checkTime() == "Old":
break
So it should return the name of sender and date recieved of all emails within the past 3 days, but instead, it returns some of the emails from the 26th (today) and then all of the emails from the 23rd (3 days ago), with none from in between. I have no idea what's causing it to do this. Any suggestions?
You are assuming that messages in the Items collection are sorted. The collection will be sorted in a particular order only after you call Items.Sort ( all_messages.Sort("[ReceivedTime]", true) in your case).
I need to calculate 90 day after last operation in user's cart!
I have model model ORDERING
class Order(DirtyFieldsMixin, models.Model):
...
items_add_date = models.DateTimeField(null=True, blank=True)
...
my task is. Track the date when user added last item in his own cart and then, if past 90 days and user not added any more items in cart sent to him email.
I'm doing this
def cart_add(request):
...
order.items_add_date = datetime.datetime.now()
order.save()
...
But what and how should I act after?
Not sure what you are struggling with but if you need to determine if its been 90 days then you would add a check:
#query for order
order = Order.get(xxx)
ninety = datetime.datetime.now() - timedelta(days=-90)
if order.items_add_date < ninety:
#send email
If you need to query for things older than 90 days:
order = Order.filter(items_add_date__lt=ninety)
I solved it so
srok = datetime.datetime.now()-timedelta(minutes=1)
user_unbuying = Order.objects.filter(items_add_date__lt=srok)
usr=[]
for unbus in user_unbuying:
if unbus.customer.id not in usr:
if unbus.customer is not None:
if unbus.items_add_date is not None:
usr.append(unbus.customer.id)
#send mail