i want to add a function to my project to return json data and display it in the main template (base.html) using ajax , this is my function
@login_required
def alerts(request):
if request.is_ajax:
sender = Post.objects.filter(active=False)
return JsonResponse(sender)
my models.py
class Post(models.Model):
title = models.CharField(max_length=50)
active = models.BooleanField(default=True)
#others
and this is my base.html
$(document).ready(function(){
$('.btn-click').click(function(){
$.ajax({
url:'/ajax/alerts/',
type:'get',
success:function(data){
document.getElementById('alerts').append(data.title)
}
})
})
})
<div x-data="{ dropdownOpen: false }">
<button @click="dropdownOpen = !dropdownOpen"
class="relative z-10 block rounded-md text-black p-2 focus:outline-none btn-click">
<i class="fas fa-bell"></i>
<!-- <img src="icon/bell.svg" class="w-5" alt=""> -->
</button>
<div x-show="dropdownOpen"
class="absolute left-2 top-10 text-right py-2 w-59 grayBG rounded-md shadow-xl z-20 h-48 overflow-y-scroll ">
<p class="whiteCOLOR text-center border-b border-red-500 p-2" id="alerts"></p>
</div>
</div>
and my urls.py
path('ajax/alerts', alerts,name='alerts'),
but it shows nothing !? and in the console log returns
http://127.0.0.1:8000/ajax/alerts/ 500 (Internal Server Error)
i want to display those posts which not accepted in an alert , thank you ..
http://127.0.0.1:8000/ajax/alerts/ 500 (Internal Server Error)sender = {'a':'b'}but the problem in the for loop i think