DEV Community

Cover image for Django ajax request with axios and vanilla javascript (Tutorial)
Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

4 1

Django ajax request with axios and vanilla javascript (Tutorial)

Hi there Nomosker,
Hope everyone well.
In this short tutorial, I will explain a bit about Django ajax with Axios.
I have seen most of the tutorials used with jquery but in some cases, we are not using jquery so instantly we can use Axios to make it easy to understand.

Let's do step by step.

1st app/urls.py

path('developer', views.Developer, name="developer")

2nd app/models.py

class DeveloperList(models.Model):
    name = models.CharField(max_length=25)
    email = models.EmailField(max_length=25)
    country = models.CharField(max_length=25)
    def __str__(self):
        return self.name
Enter fullscreen mode Exit fullscreen mode

3rd app/views.py

def Developer(request):
    developer_list = DeveloperList.objects.all()
    json_data = {}
    if request.method == 'POST':
        # get the input field name
        name = request.POST.get('name')
        email = request.POST.get('email')
        country = request.POST.get('country')

        # set in json 
        json_data['name'] = name
        json_data['email'] = email
        json_data['country'] = country

        # create the model to store in db
        DeveloperList.objects.create(
            name = name,
            email = email,
            country = country
        )
        #return the json
        return JsonResponse(json_data)

    return render(request, 'developer.html', {"developer_list": developer_list})
Enter fullscreen mode Exit fullscreen mode

4th app/templates

create templates folder and put developer.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax learning with axios</title>

</head>

<body>


    <form method="post" onsubmit="return formSubmit()">
        {% csrf_token %}
        <div class="form-group">
            <label for="" class="form-label">Name</label>
            <input type="text" name="name" class="form-control">
        </div>
        <div class="form-group">
            <label for="" class="form-label">Email</label>
            <input type="eamil" name="email" class="form-control">
        </div>
        <div class="form-group">
            <label for="" class="form-label">Country</label>
            <input type="text" name="country" class="form-control">
        </div>

        <button type="submit" class="btn btn-primary">Submit</button>
    </form>

    {% if developer_list %}
    <table>
        <thead>
            <tr>
                <th> Name </th>
                <th> Email </th>
                <th> Country </th>
            </tr>
        <tbody id="developer_list">
            {% for developer in developer_list %}
            <tr>
                <td> {{developer.name}} </td>
                <td> {{developer.email}} </td>
                <td> {{developer.country}} </td>
            </tr>
            {% endfor %}
        </tbody>
        </thead>
    </table>
    {% endif %}


    <script src='https://cdnjs.cloudflare.com/ajax/libs/axios/0.9.1/axios.js'></script>


    <script>

        function formSubmit() {
            event.preventDefault()
            axiosSetup()
        }

        function axiosSetup() {
            // for geting the input value to pass at server for collecting there value and save in db
            let data = new FormData()
            data.append('name', document.querySelector('input[name="name"]').value)
            data.append('email', document.querySelector('input[name="email"]').value)
            data.append('country', document.querySelector('input[name="country"]').value)
            data.append('csrfmiddlewaretoken', '{{csrf_token}}') // setup csrf_token as a post request

            // ....axios post request
            let url = '{% url "developer" %}' // self request so we call developer

            axios.post(url, data)
                .then(res => { 
                    document.getElementById('developer_list').innerHTML += `
                    <tr>
                        <td> ${res.data.name} </td>
                        <td> ${res.data.email} </td>
                        <td> ${res.data.country} </td>
                    </tr>
                    `
                })
                .catch(e => console.log(e))
        }



    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

5th go to terminal
run below the command one by one

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

everything is ready so now, we can run our project.

6th run project
go to terminal again by ctrl+

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

If you like this short Django tutorial don't forget to like, comment, share.
Thanks all.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more