Passing JSON data to the front end using Django

后端 未结 5 2054
旧巷少年郎
旧巷少年郎 2021-01-01 02:42

Is there a way to pass JSON objects to the front end of a web template if using the Django framework or Python in general?

For example, if I want to send an object t

相关标签:
5条回答
  • 2021-01-01 02:48

    As of Django 2.1 there is another way to pass JSON objects to the front-end by including them in the template and using the json_script template filter. This will create a script tag in the HTML and include the JSON within that. This is useful for including the JSON in the download of the HTML page.

    Your template would use the tag like so:

    {{ your_json_object | json_script: "element_id" }}
    

    Where your_json_object is a template variable containing an object that can be parsed into JSON.

    The HTML output would be:

    <script id="element_id">{['json', 'object']}</script> 
    

    And you can access it in a later Javascript file with:

    let my_json = JSON.parse(document.getElementByID('element_id').textContent)
    

    Checkout the documentation.

    0 讨论(0)
  • 2021-01-01 02:59

    If I understand you correctly, you want to render some JSON in your HTML output.

    To do this, pass the json-encoded object from the view to the template:

    views.py:

    import json
    
    def myview(request):
        obj = {"a": 1, "b": 2}
        return render_to_response("template.html", {"obj_as_json": json.dumps(obj)})
    

    template.html:

    <html>
        <head>
        <script type="text/javascript">
        var obj = {{ obj_as_json|safe }};
        </script>
        </head>
        ...
    </html>
    

    Will render as:

    ...
    <script type="text/javascript">
    var obj = {"a": 1, "b": 2};
    ...
    

    Note that json.dumps only works with dictionaries containing simple data types. Django has support for serializing model objects to json, using:

    from django.core import serializers
    obj_as_json = serializers.serialize("json", my_model_object)
    

    Update: note that you need to use "safe" to get this:

      var obj = {"items": [{"human": "Genesis", "usfm": "GEN"},],}
    

    instead of this:

      var obj = {&quot;items&quot;: [{&quot;human&quot;: &quot;Genesis&quot;, &quot;usfm&quot;: &quot;GEN&quot;},],}
    
    0 讨论(0)
  • 2021-01-01 03:00

    Sure, just setup a view that returns JSON and make a request to it. Here's a simple example:

    import json      
    from django.http import HttpResponse
    from django.template import Template, Context
    
    def ajax(request):
        """returns json response"""
        return HttpResponse(json.dumps({'foo': 'bar'}), mimetype='application/json')
    
    def index(request):
        """simple index page which uses jquery to make a single get request to /ajax, alerting the value of foo"""
        t = Template("""
        <!doctype html>
          <head>
           <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
           <script type="text/javascript">
             $.get('/ajax/', function(data) {
               alert(data['foo']);
             });
           </script>
         </head>
        </html>""")
        return HttpResponse(t.render(Context()))
    
    # urlconf
    urlpatterns = patterns('',
        (r'^$', index),
        (r'^ajax/', ajax),
    )
    
    0 讨论(0)
  • 2021-01-01 03:05

    Unfortunately, the present answers are a bit outdated, here's how to do this with more recent versions of Django (including Django > 2.0):

    Use JsonResponse, a subclass of HttpResponse, for this:

    # views.py
    from django.http import JsonResponse
    
    def get_coords(request):
        """returns json response"""
        json_data = {'xval': 10, 'yval': 10}
        return JsonResponse(json_data)
    

    It assumes a dict as parameter, but you can pass any JSON-serializable, in principle. I would discourage you from doing so, but if you pass an object that is not a dict you need to set the parameter safe=False.

    The ajax-request might look something like:

    # index.html
    ...
    <head>
    ...
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $.get("{% url 'ajax_get_coords' %}", function(data) {
            var xval = data.xval;
            var yval = data.yval;
            ...
        });
    </script>
    ...
    

    With the corresponding urlconfig:

    # urls.py
    
    urlpatterns = [
       path('ajax_coords/', views.get_coords, name='ajax_get_coords'),
       ...
    
    0 讨论(0)
  • 2021-01-01 03:13

    Complementing zeekay answer, if you want to send only an object you could do a json dump, for example:

    import json
    
    def my_ajax_view(request):
        if not request.is_ajax():
            raise Http404
    
        data_dict = getmydata() #lets supose is a dict
        return HttpResponse(json.dumps(data_dict))
    

    That way you will receive that data via your ajax success and do whatever you want with it.

    You can send over lists too, when you receive your response sometimes you will need to do a JSON.parse on data (sometimes cause when you send a dictionary I think is not necessary)

    0 讨论(0)
提交回复
热议问题