how to use django template tags on returned ajax calls?

  • Last Update :
  • Techknowledgy :

Try this instead:

def AJAXsearch(request):
   searchterm = request.GET['searchterm']
result = UserObj.objects.filter(person_name = searchterm)
return render(request, "path/to/your/template.html", {
   "result": result
})

resultlist.html:

<div id="result" >
{% for person in result %}
{{person.property}}
{%endfor%} </div>

Then in userprofile.html:

{
   # Lots of code around the result list #
} {
   % include "resultlist.html" %
} {
   # Lots of code around the result list #
}

Suggestion : 2

In simpler words, AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that updating parts of a web page is possible, without reloading the whole page. We can make AJAX requests from Django templates using JQuery. , 1 week ago The HTTP GET method is used to retrieve data from the server. In this section, we will create a signup page where we will check the availability of a username using JQuery and AJAX in Django templates. This is a very common requirement for most modern apps. views.py So here we have three views first one is the homeview which is basically rending a ... , This means that updating parts of a web page is possible, without reloading the whole page. We can make AJAX requests from Django templates using JQuery. ,The template tag loop does not do anything. In fact, I cannot manipulate/design the output at all, it is just a normal string of usernames.


$(document).ready(function() {
   $('#AJAXBox').keyup(function() {
      var searchedterm;
      searchedterm = $(this).val();
      $.get('/AJAXsearch/', {
         searchterm: searchedterm
      }, function(data) {
         $('#result').html(data);
      });
   });
});

def AJAXsearch(request): searchterm = request.GET['searchterm'] result = UserObj.objects.filter(person_name = searchterm) return render(request, "path/to/your/template.html", {
   "result": result
})
... success: function (json) {if (json.new_messages.length) {  for (let m of json.new_messages) { $('#messages-list').append("<li>"+m.sender_name+""+m.content+"</li>");  }} }, 
{% for m in messages_list %}<li><b>{{ m.sender.profile.get_short_name }}</b>({{ m.send_time|time:"H:i"}}):{{ m.content }}{% if m.sender == user %}  {% if m.is_seen %} <b><small>✓✓</small></b>  {% else %} <b><small></small></b>  {% endif %}{% endif %}</li>{% empty %}<li>No messages here yet...</li>{% endfor %} 
response = render_to_string("just_list.html", context = {
   "messages_list": new_messages
}) return JsonResponse({
   "messages": response
})
...success: function(json) {
   $('#messages-list').append(json.messages);
},

Suggestion : 3

We can make AJAX requests from Django templates using JQuery. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post and you can load the external data directly into the selected HTML elements of your web page.,In this section, we will learn how to make POST requests with JQuery and AJAX in Django templates.,In this tutorial, we will learn how to make AJAX HTTP GET and POST requests from Django templates.,In this section, we will create a signup page where we will check the availability of a username using JQuery and AJAX in Django templates. This is a very common requirement for most modern apps.

views.py

from django.contrib.auth.models
import User
from django.contrib.auth.decorators
import login_required
from django.http
import JsonResponse
from django.contrib.auth.forms
import UserCreationForm
from django.contrib.auth
import login, authenticate
from django.shortcuts
import render, redirect
from django.views.generic.edit
import CreateView
from django.urls
import reverse_lazy

@login_required
def home(request):
   return render(request, 'home.html')

class SignUpView(CreateView):
   template_name = 'signup.html'
form_class = UserCreationForm
success_url = reverse_lazy('home')

def form_valid(self, form):
   valid = super().form_valid(form)
login(self.request, self.object)
return valid

def validate_username(request):
   ""
"Check username availability"
""
username = request.GET.get('username', None)
response = {
   'is_taken': User.objects.filter(username__iexact = username).exists()
}
return JsonResponse(response)

The JsonResponse class returns an HTTP response with an application/json content type, converting the given object into a JSON object. So if the username already exists in the database it will return a JSON object as follows.

{
   'is_taken': true
}

urls.py

from django.urls
import path
from.views
import home, SignUpView, validate_username

urlpatterns = [
   path('', home, name = 'home'),
   path('signup', SignUpView.as_view(), name = 'signup'),
   path('validate_username', validate_username, name = 'validate_username')
]

signup.html

{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
        integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>

<body>
    <div class="container mt-5 w-50">
        <form id="signupForm" method="POST">
            {% csrf_token %}
            {{ form|crispy  }}
            <input type="submit" name="signupSubmit" class="btn btn-success btn-lg" />
        </form>
    </div>

    {% block javascript %}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script>
        $(document).ready(function () {
            // catch the form's submit event
            $('#id_username').keyup(function () {
                // create an AJAX call
                $.ajax({
                    data: $(this).serialize(), // get the form data
                    url: "{% url 'validate_username' %}",
                    // on success
                    success: function (response) {
                        if (response.is_taken == true) {
                            $('#id_username').removeClass('is-valid').addClass('is-invalid');
                            $('#id_username').after('<div class="invalid-feedback d-block" id="usernameError">This username is not available!</div>')
                        }
                        else {
                            $('#id_username').removeClass('is-invalid').addClass('is-valid');
                            $('#usernameError').remove();

                        }

                    },
                    // on error
                    error: function (response) {
                        // alert the error if any error occured
                        console.log(response.responseJSON.errors)
                    }
                });

                return false;
            });
        })
    </script>
    {% endblock javascript %}
</body>

</html>

Inside the head tag, we are loading the bootstrap from CDN you can download the library and serve it from static folders as well.

<form id="signupForm" method="POST">
            {% csrf_token %}
            {{ form|crispy  }}
<input type="submit" name="signupSubmit" class="btn btn-success btn-lg" />
</form>

Suggestion : 4

One way I found to solve this problem is to render the template first, and then send the resulting text in response.,In the view, using a function called render_to_string, render the template and send it in context of the json response:,In a template file, only include the html that needs to be used in Ajax. No extra html tags. Here you can use all Django tags and filters. For example:,How to render html text from database inside a django template using template tags

In a template file, only include the html that needs to be used in Ajax. No extra html tags. Here you can use all Django tags and filters. For example:

{% for m in messages_list %}
    <li>
    <b>{{ m.sender.profile.get_short_name }}</b>
    ({{ m.send_time|time:"H:i" }}):
    {{ m.content }}
    {% if m.sender == user %}
        {% if m.is_seen %}
            <b><small>✓✓</small></b>
        {% else %}
            <b><small></small></b>
        {% endif %}
    {% endif %}
    </li>
{% empty %}
    <li>No messages here yet...</li>
{% endfor %}

In the view, using a function called render_to_string, render the template and send it in context of the json response:

response = render_to_string("just_list.html", context = {
   "messages_list": new_messages
})
return JsonResponse({
   "messages": response
})

Then it can easily be used in Ajax:

...
success: function(json) {
   $('#messages-list').append(json.messages);
},

Suggestion : 5

Last Updated : 06 May, 2022

  • To Create a Django Project execute: 
$ django - admin startproject django_example
  • After creating a project we need to create a Django app. To create an app say “post” execute the following: 
$ cd django_example
$ python manage.py startapp post
  • In models.py. First, create a post table. To create a post table you’ll need to write:
class Post(models.Model):
   post_heading = models.CharField(max_length = 200)
post_text = models.TextField()
def __unicode__(self): # If python2 use __str__
if python3
return unicode(self.post_heading)
  • Make Migration and migrate step: 
$ python manage.py makemigrations
$ python manage.py migrate
  • First, import Previously created Models and HTTP response
from.models
import Post, Like
from django.http
import HttpResponse

Suggestion : 6

Aug 29, 2016

{% load static %}<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{% block title %}Default Title{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/app.css' %}">
    {% block stylesheet %}{% endblock %}
  </head>
  <body>
    <header>
      ...
    </header>
    <main>
      {% block content %}
      {% endblock %}
    </main>
    <footer>
      ...
    </footer>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script src="{% static 'js/app.js' %}"></script>
    {% block javascript %}{% endblock %}
  </body>
</html>
from django.contrib.auth.forms
import UserCreationForm
from django.views.generic.edit
import CreateView

class SignUpView(CreateView):
   template_name = 'core/signup.html'
form_class = UserCreationForm
from django.conf.urls
import url
from core
import views

urlpatterns = [
   url(r '^signup/$', views.SignUpView.as_view(), name = 'signup'),
]
{% extends 'base.html' %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}
<input type="text" required="" name="username" maxlength="150" id="id_username" autofocus="">
{% extends 'base.html' %}

{% block javascript %}
  <script>
    $("#id_username").change(function () {
      console.log( $(this).val() );
    });
  </script>
{% endblock %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

Suggestion : 7

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:,The template tags allows us to to do some programming on the server before sending HTML to the client.,In Django templates, you can perform programming logic like executing if statements and for loops.,In the next chapters you will learn about the most common template tags.

template.html:

{% if greeting == 1 %}
  <h1>Hello</h1>
{% else %}
  <h1>Bye</h1>
{% endif %}

template.html:

<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }}</li>
  {% endfor %}
</ul>