Всплывающее окно при выполнении условия if в файле views.py в django
Я хочу показать всплывающее окно вместо httpresponse, показанного ниже в файле views.py после выполнения условия if - (ниже приведен участок кода в файле views.py)
if data['check_in'] > now and data['check_out'] > now and data['check_out'] > data['check_in']:
#Check if the room is available
if available_rooms is not None:
if len(available_rooms) >= int(num_rooms_req):
for i in num_rooms_req_lst:
#Book the First available room
# print(available_rooms[i-1])
booking = book_room(request, available_rooms[i-1],data['check_in'],data['check_out'],total_cost)
return HttpResponse(booking)
else:
return HttpResponse('Only 1 rooms available in this category')
else:
return HttpResponse('All the rooms of this category are booked! Try another category!')
else:
return HttpResponse('checkin/checkout date in past or checkout date is prior to checkin date!')
Итак, в приведенном выше разделе кода views.py - что будет лучшим способом показать всплывающие окна или предупреждения о возврате HttpResponse (но предупреждения приведут меня к другому html) - я не хочу переходить от родительского html...
from django.contrib import messages
if data['check_in'] > now and data['check_out'] > now and data['check_out'] > data['check_in']:
if the room is available
if available_rooms is not None:
if len(available_rooms) >= int(num_rooms_req):
for i in num_rooms_req_lst:
booking = book_room(request, available_rooms[i-1],data['check_in'],data['check_out'],total_cost)
return HttpResponse(booking)
else:
messages.warning(request,'Only 1 rooms available in this category')
return redirect('rediect_path') #/user/login/
else:
messages.warning(request,'All the rooms of this category are booked! Try another category!')
return redirect('rediect_path') #add your rediect path
else:
messages.success(request,'checkin/checkout date in past or checkout date is prior to checkin date!')
return redirect('rediect_path')
добавьте это в свой HTML
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li class="{{ message.tags }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
Мы можем добавить эти 5 типов сообщений.
debug,info,success,warning,error.
messages.debug(request, 'Total records updated {0}'.format(count))
messages.info(request, 'Improve your profile today!')
messages.success(request, 'Your password was updated successfully!')
messages.warning(request, 'Please correct the error below.')
messages.error(request, 'An unexpected error occured.')
@Akash Nagtilak - большое спасибо за ответ. Я пытался использовать вышеуказанное, но не уверен в паре вещей -
- в rediect_path что можно указать, потому что в моем фрагменте кода, который я разместил, это раздел post в views.py, который я добавил, но в разделе get у меня есть html с контекстом, на котором я хочу остаться - для справки я вставляю полный класс views.py .
- где я должен добавить часть, которую вы дали в HTML -
class RoomDetailView(View):
def get(self, request, *args, **kwargs):
id = self.kwargs.get('id', None)
form = AvailabilityForm()
print(form)
human_format_room_category = get_room_category_human_format(id)
if human_format_room_category is not None:
context={
'room_category': human_format_room_category,
'form': form,
}
return render(request,'room_detail_view.html', context)
else:
return HttpResponse('category does not exist')
def post(self, request, *args, **kwargs):
#Get room category from kwargs
id = self.kwargs.get('id', None)
#Pass request.POST to AvailabilityForm
form = AvailabilityForm(request.POST)
#Checking form Validity
if form.is_valid(): #check the validity of the form and return the cleaned data from the form
data = form.cleaned_data
now = timezone.now()
num_rooms_req = request.POST.get('Num_Rooms')
print("no rooms requested",num_rooms_req)
num_rooms_req_lst = list(range(1, int(num_rooms_req)+1))
#Get Available Rooms
available_rooms = get_available_rooms(id, data['check_in'],data['check_out'])
# print("rooms_available",len(available_rooms))
#get the total charge for the room
total_cost = find_total_room_charge(data['check_in'],data['check_out'],id)
if data['check_in'] > now and data['check_out'] > now and data['check_out'] > data['check_in']:
#Check if the room is available
if available_rooms is not None:
if len(available_rooms) >= int(num_rooms_req):
for i in num_rooms_req_lst:
#Book the First available room
# print(available_rooms[i-1])
booking = book_room(request, available_rooms[i-1],data['check_in'],data['check_out'],total_cost)
return HttpResponse(booking)
else:
messages.warning(request,'Only 1 rooms available in this category')
return HttpResponse('redirect_path')
else:
return HttpResponse('All the rooms of this category are booked! Try another category!')
else:
return HttpResponse('checkin/checkout date in past or checkout date is prior to checkin date!')
@ Омайер Хасан Мариф - спасибо за ответ
Мне нужно всплывающее окно из html, которое я вызываю в секции get вышеприведенного фрагмента кода, которым я поделился, т.е. - room_detail_view.html
не уверен, что понял про API...