I want to call the django view from client side that will display all the messages from the models on the html page
AJAX function
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'GET',
url : "/load_with_room_name/{{room_name}}/",
success: function(response){
console.log(response);
$("#display").empty();
},
error: function(response){
alert('An error occured')
}
});
},1000);
})
</script>
django view function
def load_with_room_name(request,room_name):
try:
current_user = Account.objects.get(email=str(request.user))
chat_room = ChatRoom.objects.get(room_name=room_name)
if chat_room.room_user_1 == current_user or chat_room.room_user_2 == current_user:
print(current_user)
return redirect('room',room_name,current_user.username)
else:
return redirect('chat')
except Exception as e:
log_exception(request,e,view_name="load_with_room_name")
return render(request,"error.html")
django urlpattern for the above view
urlpatterns = [ path('load_with_room_name/<str:room_name>',views.load_with_room_name,name='load_with_room_name'),
]
CodePudding user response:
while you have already tested that it works by accessing it correctly in your django project only I see that you would only need to add the full path as follows
url : window.location.origin "/load_with_room_name/{{room_name}}/",
CodePudding user response:
change url to
url : "{% url 'load_with_room_name' room_name %}",
in order to use the django url-pattern and be aware of the trailing slash in your original code. There is no trailing slash in your url-pattern!