0

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 ..

9
  • Check your browser console if there are any errors. Also, try to print the JsonResponse and see if it actually returns anything. Commented May 4, 2021 at 9:34
  • it return http://127.0.0.1:8000/ajax/alerts/ 500 (Internal Server Error) Commented May 4, 2021 at 9:43
  • 2
    So, the problem is with your view logic. Try to see what error occurs,it should display in your Django server log. Commented May 4, 2021 at 9:46
  • it works for sender = {'a':'b'} but the problem in the for loop i think Commented May 4, 2021 at 9:51
  • What error is returned from Django when the ajax call is made? Commented May 4, 2021 at 9:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.