I am using calendar on my server. The current day should be marked but it is not refreshing it. As a result, marked day is the day of server restart. Do you have any solution to this issue? I want it to mark correct day, not the day on which server occurred. Thanks for help.
UPDATE
This is the code i use
This is entire view function
today = datetime.datetime.today()
#pulling models from database
employee = Employee.objects.filter(barberName=Barber)
reservations = Appointments.objects.all()
apptDict = {}
timeList = []
#make list of all possible appointments for the day
for x in employee:
startTime = "28/02/22 " + str(x.barberStartTime)
endTime = "28/02/22 " + str(x.barberEndTime)
startTimeObj = datetime.datetime.strptime(startTime, '%d/%m/%y %H:%M:%S')
endTimeObj = datetime.datetime.strptime(endTime, '%d/%m/%y %H:%M:%S')
while startTimeObj < endTimeObj:
justTimeList = str(startTimeObj).split(" ")[1].split(":")
timeList.append(justTimeList[0] + ":" + justTimeList[1])
startTimeObj += datetime.timedelta(hours=0.5)
apptDict["possibleTimes"] = timeList
#make dictionary of already made appointments in form "date": ["time1", "time2", "timeN"]
for reservation in reservations:
time = str(reservation.time).split(":")
timeStr = time[0] + ":" + time[1]
if str(reservation.date) not in apptDict:
apptDict[str(reservation.date)] = []
apptDict[str(reservation.date)].append(str(timeStr))
if reservation.date < today.date():
apptDict[str(reservation.date)] = ["Over"]
#write to json file
with open("reservations/static/reservations/scripts/appointments.json", "w") as outfile:
json_object = json.dumps(apptDict, indent=4)
outfile.write(json_object)
context = {
"place": Place,
"barber": Barber,
"service": Service,
"calendar": newCalendar(datetime.datetime.today().month, datetime.datetime.today().year, Barber),
"employee": employee,
"availableTimes": timeList,
"apptDict": apptDict,
"availTimes": timeList
}
if request.method == "POST":
postCopy = request.POST.copy()
postCopy['time'] = datetime.datetime.strptime('15/05/22 ' + postCopy['time'], '%d/%m/%y %H:%M').time()
postCopy['phone'] = str(postCopy['phone'])
request.POST = postCopy
form = AppointmentForm(request.POST or NONE)
if form.is_valid():
form.save()
return render(request, 'reservations/reserved.html', context)
return render(request, 'reservations/reservationTime.html', context)
This is the part of calendar function. It is supposed to visually mark previous days
for x in range(1, int(today.day)):
cal = cal.replace(">" + str(x) + "<", 'style="color: #808080;">' + str(x) + "<") #marking previous days in month
Related
The context within the first conditional statement is delivered well, but the context updated within the second conditional statement is not delivered in HTML.
For example, 'MODEL_LIST' in first context is delivered well, but 'mape_val' in second context is not. I want it to be delivered.
How Can I solve this problem ?
<views.py function CODE>
def csv_forecast(request):
context = {}
username = request.user
if request.method == 'POST' and request.FILES.get('csvfile'):
uploaded_file = request.FILES.get('csvfile')
p_data = pd.read_csv(uploaded_file)
p_data.reset_index(drop=True, inplace=True)
columns_list = list(p_data.columns)
columns_list = [column.lower() for column in columns_list]
p_data.columns = columns_list
os.makedirs('media/csv', exist_ok=True)
p_data.to_csv(f'media/csv/{username}.csv', index=False)
start_date = p_data.loc[0, 'date']
len_date = int(len(p_data)*0.8)
end_date = p_data.loc[len_date, 'date']
datas = []
for i in range(1, len(columns_list)):
datas.append(columns_list[i])
MODEL_LIST = ['ARIMA', 'EMA5', 'LSTM']
context = {'datas' : datas, 'd' : p_data, 'columns_list' : columns_list, 'MODEL_LIST' : MODEL_LIST,
'start_date' : start_date, 'end_date' : end_date}
if request.POST.get('sendModel') and request.POST.get('sendPdata') and request.POST.get('sendRdata'):
send_pdata = request.POST.get('sendPdata')
send_rdata = request.POST.get('sendRdata')
send_model = request.POST.get('sendModel')
cleaned_pdata = re.split(r'[\[\],"]', send_pdata)
cleaned_rdata = re.split(r'[\[\],"]', send_rdata)
cleaned_model = re.split(r'[\[\],"]', send_model)
selected_pdata = [i for i in cleaned_pdata if len(i) >= 1]
selected_rdata = [i for i in cleaned_rdata if len(i) >= 1]
selected_model = [i for i in cleaned_model if len(i) >= 1]
csv_data = pd.read_csv(f'media/csv/{username}.csv')
mape_val, y_pred, y_test, test_date = model_main(csv_data, selected_pdata,selected_rdata, selected_model)
mape_val = float(mape_val)
print(mape_val)
fs = FileSystemStorage(location=f'media/csv/')
fs.delete(f'{username}.csv')
context.update({'mape_val':mape_val, 'y_pred':y_pred, 'y_test':y_test, 'test_date':test_date})
return render(request, 'csv_forecast.html', context)
HTML CODE PICTURE
HTML PAGE PICTURE
Debugging
Debug Console
I am trying to get third button to work on a simple app I am making. I set up if statements to detect the value of the request for two buttons, but I am getting stuck on how to configure the logic statement to get a third parameter through.
My issue is that I need to have the form filled with any data before the subscriptions button will work properly. When the form is blank the app will indicate the form needs to be filled out. I am not familiar with javascript to have the buttons run from that. My hope is that I can learn how to configure the if statement to have the subscriptions call work without the form being filled out.
Below is the UI as and the views.py def. The Amount and Delete functions work fine. It is just the subscription button that won't work until I put literally any data into the two text fields fields.
def usage(request):
if request.method == 'POST':
form = UsageForm(request.POST)
if form.is_valid():
if request.POST.get('subscription') == 'Subscription':
dt = datetime.today()
month = dt.month
year = dt.year
day = calendar.monthrange(year, month)[1]
eom = str(month) + "/" + str(day) + "/" + str(year)
anchor = int(time.mktime(datetime.strptime(eom, "%m/%d/%Y").timetuple()) + 68400)
cust_list = json.loads(str(stripe.Customer.list(limit=100)))
for item in cust_list['data']:
try:
print(item['subscriptions']['data'][0]['id'], item['email'], item['id'])
except:
stripe.Subscription.create(
customer=item['id'],
items=[{'plan': 'plan_DFnNVzXKJ2w0Ad'}],
billing_cycle_anchor=anchor,
)
if request.POST.get('delete') == 'Delete':
cust_info = custinfo.objects.all()
cust_info.delete()
all_custinfo_items = custinfo.objects.all()
else:
Sub_ID = form.cleaned_data['Sub_ID']
amount = form.cleaned_data['amount']
stripe_data = stripe.SubscriptionItem.list(subscription=Sub_ID)
sub_item = stripe_data["data"][0]["id"]
stripe.UsageRecord.create(
quantity=amount,
timestamp=int(time.time()),
subscription_item=sub_item,
action='increment')
form.save()
print("Last Ran: ", Sub_ID, amount)
all_custinfo_items = custinfo.objects.all()
return render(request, 'form.html', {'form': form, 'custinfo_items': all_custinfo_items})
else:
form = UsageForm()
# all_subid_items = custinfo.objects.filter(Sub_ID__startswith='sub')
return render(request, 'form.html', {'form': form})
Under the "send_mail" function, I would like to change the "start" variable to display the date/time as MM/DD/YYYY - HH:MM AM/PM in the email. Does someone know how to do this?
Thank you in advance!
date = coerce_date_dict(request.GET)
initial_data = None
if date:
try:
start = datetime.datetime(**date)
initial_data = {
"start": start,
"end": start + datetime.timedelta(minutes=60)
}
except TypeError:
raise Http404
except ValueError:
raise Http404
instance = None
if event_id is not None:
instance = get_object_or_404(Event, id=event_id)
calendar = get_object_or_404(Calendar, slug=calendar_slug)
form = form_class(data=request.POST or None, instance=instance, initial=initial_data)
if form.is_valid():
event = form.save(commit=False)
if instance is None:
event.creator = request.user
event.calendar = calendar
try:
send_mail('New Lesson', '%s has scheduled a new lesson for %s' %(request.user.full_name, start), 'example#gmail.com', ['example#gmail.com'])
except:
pass
event.save()
next = next or reverse('event', args=[event.id])
next = get_next_url(request, next)
return HttpResponseRedirect(next)
start is a datetime.datetime object, so we can call its strftime method to generate a formatted string.
The format specifier you want is %m/%d/%Y %I:%M %p
For example, the strftime method called on the current time (for me, on the East Coast of US) generated: 03/17/2015 05:51 PM
Which we can easily integrate into your code with:
start = datetime.datetime(**date)
initial_data = {
"start": start.strftime("%m/%d/%Y %I:%M %p"),
"end": start + datetime.timedelta(minutes=60)
}
Note: You'll have to ensure that making this change doesn't break anything else "down the road" -- as initial_data['start'] was a datetime.datetime object, and is now a string.
I have a form that accepts a single date, or a date range. The date is then passed to a subsequent view that queries the DB and produces a result. I've managed to pass the single date via the URL
but I have yet to find a means to pass the date range from the form to the subsequent view where the query is run.
( Note: I understand that the indentation of the form presented below is off. For some this is my first post and I'm not yet wise to all the subtleties of stack overflow)
class Date_rangeFRM(forms.Form):
Single_date = forms.DateField(required=False)
Date_start = forms.DateField(required=False)
Date_end = forms.DateField(required=False)
def date_range(request):
context = RequestContext(request)
if request.method == 'POST':
form = Date_rangeFRM(request.POST)
print "valid", form.is_valid()
print "form", str(form)
if form.is_valid():
#print "form", str(form)
Single_date = form.cleaned_data['Single_date']
Date_start = form.cleaned_data['Date_start']
Date_end = form.cleaned_data['Date_end']
if Single_date != "":
#print "redirecting to Dav View:", '/counter/%02d-%02d-%02d/Day_view/' %(Single_date.year,Single_date.month,Single_date.day)
return HttpResponseRedirect('/counter/%02d-%02d-%02d/Day_view/' %(Single_date.year,Single_date.month,Single_date.day))
else:
#****passing Magic ********
return HttpResponseRedirect('/counter/History_View/')
else:
print form.errors
else:
form = Date_rangeFRM()
return render_to_response('counter/historyFRM.html', {'form':form}, context)
def History_View(request):
context = RequestContext(request)
#****** Receiving magic********
date_start = form.cleaned_data['date_start']
date_end = form.cleaned_data['date_end']
context['meal_list'] = meal_list
context['comp_list'] = comp_list
context['day_list'] = day_list
dt_range = []
day_list = RecordedDays.objects.filter(profile= request.user.userprofile,
Date__gte = date_start, Date__lte = date_end )
for day in day_list:
dt_range.append(day.Date)
meal_list = MealType.objects.filter(
newDay__profile = request.user.userprofile,
newDay__Date__gte = date_start, newDay__Date__lte = date_end )
#newDay__Date= date( int(year), int(month), int(day) ) )
for meal in meal_list:
dt_range.append([ meal.get_mealNum_display(), meal.Mealtotal() ])
comp_list =Ingredient.objects.filter(numMeal = meal)
for comp in comp_list:
dt_range[-1].append([comp.component, comp.comp_total()] )
return render_to_response('counter/history_view.html', context
Also I'm not entirely sure I'm using the __lte, __gte feature correctly. If you could please inspect it. Much appreciated.
Thanks One and all for your Help.
I new with python and django, currently I little a bit confused about how to do my project.
Scenario is simple:
User by using form on fronted is requested weekly statistic of customers and should get list of statistic per customer on selected period (year, week)
So far I able to query data from raw database, function for count statistic start_date and end_date of selected week working fine.
in my models.py
def WeekRange(year, week):
d = date(year, 1, 1)
delta_days = d.isoweekday() - 1
delta_weeks = week
if year == d.isocalendar()[0]:
delta_weeks -= 1
delta = timedelta(days=-delta_days, weeks=delta_weeks)
weekbeg = datetime.datetime.combine(d, datetime.time(00, 00, 01)) + delta
delta2 = timedelta(days=6-delta_days, weeks=delta_weeks)
weekend = datetime.datetime.combine(d, datetime.time(23, 59, 59)) + delta2
cursor = connections['nocdb'].cursor()
cursor.execute("SELECT DISTINCT (p.name) AS platform, count(e.id ) AS count FROM event e, lu_platform p WHERE e.platform_id = p.id AND e.sourcetype_id = 1 AND e.event_datetime BETWEEN %s AND %s AND e.sender_id NOT IN ( 759, 73 ) GROUP BY p.name ORDER BY p.name", [weekbeg, weekend] )
results = cursor.fetchall()
return results
view.py
def WeekRequestForm(request):
form = WeekSelection()
year = request.POST.get("q_year", "")
week = request.POST.get("q_week", "")
currstat_b = [year, week]
weekstat = WeekRange(*currstat_b)
return render_to_response('form.html', {'weekstat': weekstat, 'form': form}, context_instance=RequestContext(request))
forms.py
YEARCHOICE = tuple((str(n), str(n)) for n in range(2011, datetime.now().year + 1))
WEEKCHOICE = range(1, 53)
class WeekSelection(forms.Form):
q_year = forms.ChoiceField(label='Year', choices=YEARCHOICE, initial=(datetime.today().isocalendar()[0]))
q_week = forms.ChoiceField(label='Week', choices=zip(WEEKCHOICE, WEEKCHOICE), initial=(datetime.today().isocalendar()[1]))
With followings I get "an integer is required"
after replace currstat_b = [2013, 48] everything working fine and show me statistick of week 48.
Problem is how to get selected numbers from form to argument in weekstat = WeekRange(*currstat_b)
Also I not sure if is better put raw data function in views or in models as is now.
I will be appreciated for any tip
Maybe passing data through form could help, try this:
def WeekRequestForm(request):
form = WeekSelection()
weekstat = None
if request.method == "POST":
form = WeekSelection(request.POST)
if form.is_valid():
year = int(form.cleaned_data["q_year"])
week = int(form.cleaned_data["q_week"])
currstat_b = [year, week]
weekstat = WeekRange(*currstat_b)
return render_to_response('form.html', {'weekstat': weekstat, 'form': form},
context_instance=RequestContext(request))