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
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
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})
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})
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>
<!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>
<!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
python manage.py makemigrations
python manage.py migrate
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
python manage.py runserver
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.

原文链接:Django ajax request with axios and vanilla javascript (Tutorial)

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
No one can change another. But one can be the reason for another to change.
没人能改变另一个人,但是某个人能成为一个人改变的原因
评论 抢沙发

请登录后发表评论

    暂无评论内容