简体   繁体   English

使用Ajax,jQuery将数据发布到Django

[英]Posting data to Django with Ajax, jQuery

I would like to submit the html5 geolocation data to the django admin backend. 我想将html5地理位置数据提交到django管理员后端。 However I am not sure if the javascript, jQuery and ajax is set up correctly in the index.html javascript . 但是我不确定在index.html javascript中是否正确设置了javascript,jQuery和ajax。 I am able to display the latitude and longitude in the html page but am unable to post the data to django. 我能够在html页面中显示纬度和经度,但无法将数据发布到django。 Is there someone kind enough to help correct where I might have gone wrong. 是否有足够的人帮助纠正我可能出了问题的地方。 I have been working on it for a week being a newbie. 作为新手,我已经为它工作了一个星期。 Would truly appreciate any help. 衷心感谢您的帮助。 Thank you. 谢谢。

The code that works so far is below. 到目前为止有效的代码如下。 The file structure of the django app is as below: django应用程序的文件结构如下:

-ajax
   - __pycache__
   - migrations
        - __pycache__
          0001_initial.py
          __init__.py
   - static
        - css
            - bootstrap.css
        - fonts
        - js
            - script.js
   - templates
        - ajax
            - base.html
            - index.html
        - __init__.py
        - admin.py
        - apps.py
        - models.py
        - tests.py
        - urls.py
        - views.py

-server
   - __pycache__
   - __init__.py
   - settings.py
   - urls.py
   - views.py
   - wsgi.py

-db.sqlite3
-manage.py

index.html index.html

{% extends 'ajax/base.html' %}
{% block body %}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Get Your Location</button>
<p id="demo"></p>
<button type="button" id="btn_submit" class="btn btn-primary form-control" disabled>Submit</button>
{% endblock %}

script.js script.js

var pos;

var $demo;

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    $demo.text("Geolocation is not supported by this browser.");
  }
}

function showPosition(position) {
  pos = position;
  var { latitude, longitude } = pos.coords;
  $demo.html(`Latitude: ${latitude}<br>Longitude: ${longitude}`);
  $('#btn_submit').attr("disabled", null);
}

$(document).ready(function() {
  $demo = $("#demo");
  $('#btn_submit').on('click', function() {
    var data = pos.coords;
    data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
    $.post("/echo/html/", data, function() {
      alert("Saved Data!");
    });
  });
});

base.html base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'ajax/css/bootstrap.css' %}"/>
</head>
<body>
    {% csrf_token %}
    <nav class="navbar navbar-default">
        <div class="container-fluid">
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">Python - Django Simple Submit Form With Ajax</h3>
        <hr style="border-top:1px dotted #000;"/>
        {% block body %}
        {% endblock %}
    </div>
</body>
<script src = "{% static 'ajax/js/jquery-3.2.1.js' %}"></script>
<script src = "{% static 'ajax/js/script.js' %}"></script>
</html>

admin.py 管理员

from django.contrib import admin
from .models import Member
# Register your models here.

admin.site.register(Member)

models.py models.py

from django.db import models

# Create your models here.

class Member(models.Model):
    latitude = models.DecimalField(max_digits=19, decimal_places=16)
    longitude = models.DecimalField(max_digits=19, decimal_places=16)

views.py (ajax app) views.py(ajax应用)

from django.shortcuts import render, redirect
from .models import Member
#from django.views.decorators.csrf import csrf_exempt
# Create your views here.
#@csrf_exempt
def index(request):
    return render(request, 'ajax/index.html')

#@csrf_exempt 
def insert(request):
    member = Member(latitude=request.POST['latitude'], longitude=request.POST['longitude'])
    member.save()
    return redirect('/')

urls.py (ajax app) urls.py(ajax应用)

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^insert$', views.insert, name="insert")
]

views.py (server) views.py(服务器)

from django.shortcuts import redirect

def index_redirect(request):
    return redirect('/ajax/')

urls.py (server) urls.py(服务器)

from django.conf.urls import url, include
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^$', views.index_redirect, name="index_redirect"),
    url(r'^ajax/', include("ajax.urls")),
    url(r'^admin/', admin.site.urls),
]

The most probable reason is because you don't have the CSRF Token tag in the template. 最可能的原因是因为模板中没有CSRF令牌标记。

You have to put it in the template like this: 您必须像这样将其放入模板中:

{% csrf_token %}

You can also define that a view doesn't need the CSRF Token putting the decorator csrf_exempt : 您还可以定义视图不需要CSRF令牌,将装饰器csrf_exempt放入

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

Hope that it helps you! 希望对您有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM