json,django,django-templates,django-rest-framework , How to work with django-rest-framework in the templates

How to work with django-rest-framework in the templates


Tag: json,django,django-templates,django-rest-framework

Please bear with me. I am just learning django-rest-framework. And I really can't seem to grab it.


class Day(models.Model):
    date = models.DateField(default=date.today)

class ToDo(models.Model):
    date = models.ForeignKey(Day)
    name = models.CharField(max_length=100)
    very_important = models.BooleanField(default=False)
    finished = models.BooleanField(default=False)

normal view:

def home(request):
    days = Day.objects.all()

    return render(request, 'test.html', {

Created a serializers.py file:

class DaySerializer(serializers.ModelSerializer):
    class Meta:
        model = Day
        field = ('id', 'date')

class ToDoSerializer(serializers.ModelSerializer):
    date = DaySerializer()
    class Meta:
        model = ToDo
        field = ('id', 'date', 'name', 'very_important', 'finished')

After this I am lost. Suppose I go to url('^api/$'), how do I get the json objects of Day and its related object?

Basically this is how I want to be displayed:

enter image description here

Now how can I work with django-rest-framework to look like the above in the template.


I would like to do something like this:

  1. Get the json objects by going to a url (eg: /api/.json)

            "id": 1,
            "date": "2015-06-23",
            "day_todo_set": [
                    "name": "Bloom",
                    "very_important": True,
                    "finished": False
                    "name": "REST",
                    "very_important": True,
                    "finished": True
            "id": 2,
            "date": "2015-06-22",
            "day_todo_set": [
                    "name": "Alarm 1",
                    "very_important": True,
                    "finished": True
                    "name": "Meet up with SIS",
                    "very_important": True,
                    "finished": False
                    "name": "Buy Milk",
                    "very_important": True,
                    "finished": False
  2. Manipulate objects


$(function () {
    var $days = $('#days')

        type: 'GET',
        url: '/api/.json',
        success: function(days) {
            $.each(days, function(i, day) {
                $days.append('<li>date: '+ day.date+ '</li>')



class Day(models.Model):
    date = models.DateField(default=date.today)

    def get_todo_list(self):
        return self.day_todo_set.order_by('-id')[:5] 

class ToDo(models.Model):
    date = models.ForeignKey(Day, related_name="day_todo_set")
    name = models.CharField(max_length=100)
    very_important = models.BooleanField(default=False)
    finished = models.BooleanField(default=False)

In serializers.py

class ToDoSerializer(serializers.ModelSerializer):

    class Meta:
        model = ToDo
        field = ('id', 'date', 'name', 'very_important', 'finished')

class DaySerializer(serializers.ModelSerializer):

    day_todo_set = ToDoSerializer(many=True, source="get_todo_list")

    class Meta:
       model = Day
       field = ('id', 'date', 'day_todo_set')

Write a django view using your serializer.

def day_list(request):
    List all code snippets, or create a new snippet.
    if request.method == 'GET':
        snippets = Day.objects.order_by('-date')[:10]
        serializer = DaySerializer(snippets, many=True)
        return JSONResponse(serializer.data)

In your urls.py

url(r'^api/$', views.day_list, name='days_list')


How to use template within Django template?

I have the django template like below: <a href="https://example.com/url{{ mylist.0.id }}" target="_blank"><h1 class="title">{{ mylist.0.title }}</h1></a> <p> {{ mylist.0.text|truncatewords:50 }}<br> ... (the actual template is quite big) It should be used 10 times on the same page, but 'external' html elements are different: <div class="row"> <div class="col-md-12 col-lg-12 block block-color-1"> *django...

Response 200 OK but Jquery shows error?

I am stuck in kind of a weird problem where I am trying to make a JSONP request to the Open Weather history API to get the weather information for the previous years on the a particular date. fetchHistoryUrl = ''; $.ajax({ method: 'get', url: fetchHistoryUrl, success: function(response){ console.log(response); },...

How to work with django-rest-framework in the templates

Please bear with me. I am just learning django-rest-framework. And I really can't seem to grab it. model: class Day(models.Model): date = models.DateField(default=date.today) class ToDo(models.Model): date = models.ForeignKey(Day) name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) normal view: def home(request): days = Day.objects.all() return render(request, 'test.html', { 'days':days })...

php array returns undefined but print_r shows otherwise [duplicate]

This question already has an answer here: PHP: “Notice: Undefined variable” and “Notice: Undefined index” 11 answers foreach($jsonmediationinfo as $value1) { echo $value1['mstatus']; print_r($jsonmediationinfo); } Output: 1Array ( [0] => Array ( [mstatus] => 1 [mhearingnum] => first [mminutes] => adakjaflafjlarjkelfkalfkd;la ) [1] => Array ( [mhearingnum] => second...

Call function on Server from iOS app - Objective C

If you are familiar with Parse.com's Javascript SDK, this is what I am trying to do for my own server for my iOS app (Objective-c). I want to be able to send some a string to the function that is on my server, have the server run its function and...

Codeigniter Select JSON, Insert JSON

I have very simple users database: user_id, user_name, user_email My model this: class Users extends CI_Model { private $table; private $table_fields; private $table_fields_join; function __construct() { parent::__construct(); $this->table = 'users'; $this->table_fields = array( $this->table.'.user_id', $this->table.'.user_name', $this->table.'.user_email' ); $this->table_fields_join = array(); } function select(){ $this->db->select(implode(', ', array_merge($this->table_fields, $this->table_fields_join)));...

String comparison in AngularJS

I'm trying to compare two strings in AngularJS, and I've seen examples online. As I understand it, you can use angular.equals(str1, str2), you can use ===, you can use == if you're sure that both are strings... I've tried all three, but I don't get the result. Something must be...

Create angular page in Django to consume data from JSON

In an angular controller I have a list of items: app.controller('MainController', ['$scope', function($scope) { $scope.items = [ {"foo":"bar 1"}, {"foo":"bar 2"}, {"foo":"bar n"} ] }]); The following html page, based on angular, displays a list of item: <!DOCTYPE html> <html> <head> <title>list</title> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body data-ng-app="myApp"> <div data-ng-controller="MainController">...

Use JSON file to insert data in database

I'm using my JSON file like this to insert data in my collection : var content = JSON.parse(Assets.getText('test.json')); console.log('inserting...'); Profiles.insert({ user: id, data:content }; But I would like to have a "data's tree" like that : [ user: "rtegert23423131", firstname:"test", surname:"test2", // ... ] Not like that : [ user:...

Can't save json data to variable (or cache) with angularjs $http.get

I have weird angularjs problem. I'm trying to fetch data from Rest Webservice. It works fine, but I can't save json data to object. My code looks like: services.service('customerService', [ '$http', '$cacheFactory', function($http, $cacheFactory) { var cache = $cacheFactory('dataCache'); var result = cache.get('user'); this.getById = function(id){ $http.get(urlList.getCustomer + id).success(function(data, status,...

Sencha/Extjs rest call with all parameters

I'm using ExtJs 5.1.1 and I've written a simple view with a grid, and selecting one row the corresponding model property are editable in some text fields. When editing is completed the button 'save' call Model.save() method, which use the rest proxy configured to write the changes on the server....

Link to another resource in a REST API: by its ID, or by its URL?

I am creating some APIs using apiary, so the language used is JSON. Let's assume I need to represent this resource: { "id" : 9, "name" : "test", "customer_id" : 12, "user_id" : 1, "store_id" : 3, "notes" : "Lorem ipsum example long text" } Is it correct to refer...

Parsing Google Custom Search API for Elasticsearch Documents

After retrieving results from the Google Custom Search API and writing it to JSON, I want to parse that JSON to make valid Elasticsearch documents. You can configure a parent - child relationship for nested results. However, this relationship seems to not be inferred by the data structure itself. I've...

Django: html without CSS and the right text

First of all, this website that I'm trying to build is my first, so take it easy. Thanks. Anyway, I have my home page, home.html, that extends from base.html, and joke.html, that also extends base.html. The home page works just fine, but not the joke page. Here are some parts...

How can I fill the table? (Python, Django)

I faced with a problem: I have 4 lists with data. And I need to fill the table with this data. It is the example of table: So, as you already understood, at first column must be data from a first list, at second - second list, ... I tried...

KendoUI Grid - Complex JSON with inconsistent keys

I know this is probably been asked before, but having tried to find an answer - I am guessing either I am not comprehending some of the answers right, or I am looking at the problem all wrong. I am using a complex SLC loopback query - and the api...

convert from json to array

I am trying to get data to display in a table. I don't know what I am doing wrong, but when I get the data from my page it is an array of single characters. I could parse this myself but would prefer to know what I am doing wrong....

Callable in model field not called upon adding new object through Django admin

In https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.Field.default we read that the callable of a default field value is called, every time a new object is created. In my model I have: when_first_upload = models.DateTimeField(default=datetime.datetime.now()) When in the admin page I create a new object I always get the same datetime, as if the callable is...

Parse JSON output from AlamoFire

I am using the latest Alamofire to manage a GET http request to my server. I am using the following to GET and parse the JSON: Alamofire.request(.GET, "*******") .responseJSON {(request, response, JSON, error) in if let statusesArray = JSON as? NSArray{ if let aStatus = statusesArray[0] as? NSDictionary{ //OUTPUT SHOWN...

access the json encoded object returned by php in jquery

I want to post some data to php function by ajax, then get the encoded json object that the php function will return, then I want to get the information (keys and values) from this object, but I don't know how, here is my code: $.ajax({ url: "functions.php", dataType: "JSON",...

Fatal error catched by register_shutdown_function and update json_encode

I can catch a fatal error with register_shutdown_function('shutdown') function shutdown(){ $error = error_get_last(); $result['message'] = $error['message']; } and I have an echo json_encode($result); Unfortunately this echo json_encode shows nothing because json is not updated with the message of the fatal error. What can I do to fix this?...

Nested JSON structure to build side-by-side d3.js charts

I'm currently stuck on how to traverse a JSON structure (I created) in order to create side-by-side donut charts. I think I've created a bad structure, but would appreciate any advice. I'm working from Mike Bostock's example here: http://bl.ocks.org/mbostock/1305337 which uses a .csv file for source data. In that example...

Check for duplicates in JSON

I have a json object: var object1 = [{ "value1": "1", "value2": "2", "value3": "3", }, { "value1": "1", "value2": "5", "value3": "7", }, { "value1": "6", "value2": "9", "value3": "5", }, { "value1": "6", "value2": "9", "value3": "5", }] Now I want to take each record out of that...

Show message when there's no excerpt - Django templates

I have this field on a Django template: <p class="border_dotted_bottom"> {{ expert.description|slice:":300" }} <a href="{% url 'profile' expert.username %}">{% trans "read more" %}</a>.... </p> If this object (user) has no 'decription' (a text field) it shows the word 'None', I need to get rid of that, maybe if he doesn't...

Django block inclusion not working. What did I miss?

In my base.html file I have this: {% block menu %}{% endblock menu %} and in base_menu.html I have this: {% extends "base.html" %} {% block menu %} <nav class="navbar navbar-inverse navbar-fixed-top"> ... stuff ... </div> {% endblock menu %} I would expect the menu html to show where the...

do calculation inside JSONArray in Java

I have a simple issue but cannot solve it as I am not very good at algorithm! I have an JSONArray in this form: [{"values":[{"time":1434976493,"value":"50"}, {"time":1434976494,"value":"100"}],"counter":"counter1"}, {"values":[{"time":1434976493,"value":"200"}, {"time":1434976494,"value":"300"}],"counter":"counter2"}, {"values":[{"time":1434976493,"value":"400"}, {"time":1434976494,"value":"600"}],"counter":"total"}] What I want to do is to get the integer value for counter 1 and counter 2 and then divide...

Django listview clone selected record

From an existing LISTVIEW is there a simple way to create a new record based on existing previos record? 1) select the record 2) call the CREATEVIEW 3) set as initail the data from point 1) would this be possible and which is best? A) Get data from 1) by...

Create n:m objects using json and sequelize?

I am trying to learn sequelize, but am having trouble getting a n:m object created. So far I have my 2 models that create 3 tables (Store, Product, StoreProducts) and the models below: models/Store.js module.exports = (sequelize, DataTypes) => { return Store = sequelize.define('Store', { name: { type: DataTypes.STRING, },...

Replacing elements in an HTML file with JSON objects

I am writing some Javascript to: Read in and Parse a JSON file Read in an HTML file (created as a template file) Replace elements in the HTML file with elements from the JSON file. It is only replacing the first element obj.verb. Can someone please help me figure out...

Insert data in collection at Meteor's startup

I would like to insert data at Meteor's startup. (And after from a JSON file) At startup, I create a new account and I would like to insert data and link it to this account once this one created. This is the code that creates the new account at startup:...

Use django to expose python functions on the web

I have not worked with Django seriously and my only experience is the tutorials on their site. I am trying to write my own application now, and what I want is to have some sort of API. My idea is that I will later be able to use it with...

Django test RequestFactory vs Client

I am trying to decide whether I should use Django's Client or RequestFactory to test my views. I am creating my server using DjangoRESTFramework and it's really simple, so far: class SimpleModelList(generics.ListCreateAPIView): """ Retrieve list of all route_areas or create a new one. """ queryset = SimpleModel.objects.all() serializer_class = SimpleModelSerializer...

How to rearrange CSV / JSON keys columns? (Javascript)

I am converting a JSON object array to CSV using Papa Parse JavaScript Library. Is there a way to have the CSV columns arranged in a certain way. For e.g; I get the column as: OrderStatus, canOp, OpDesc, ID, OrderNumber, FinishTime, UOM, StartTime but would like to be arranged as:...

How can I resolve my variable's unexpected output?

I have a variable in django named optional_message. If I debug the variable then it says Swenskt but when I try to print the variable on my page the following comes out: (u'Swenskt',) and the variable can't be tested for its length etc. What should I do if I only...

Sorting in Ruby on rails

I'm very new to Ruby on rails. I try to edit the following api. I want to sorting "can_go" which is true are shown at the top of list. I added this row before sending data, but the result is still order by "user_id". user_infos.sort { |a, b| - (a['can_go']<=>b['can_go'])...

Serializing a java bean into a cookie: Is it bad?

In the organization that i work for, there was a serious debate about the following. Scenario: There is a POJO with 6 different properties all are of type Strings. These values need to be persisted as cookies so that it can be picked back when someone does a booking on...

Django: show newlines from admin site?

This is probably very simple. My database objects have a TextField. Now, when I add the contents of the TextFields to an html paragraph, there are no new lines. How can I make Django show those newlines? Thank you!

why i don't get return value javascript

When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN function createCheckBoxPlatform(data) { var platform = ""; $.each(data, function (i, item) { platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' +...

Django template not found in main project directory error

I am getting a 'template not found' error, although I've set up a correct template hierarchy (or so I thought) . ├── manage.py ├── twinja │   ├── admin.py │   ├── admin.pyc │   ├── __init__.py │   ├── __init__.pyc │   ├── migrations │   │   ├── __init__.py │   │   └── __init__.pyc │   ├──...

Why i get can not resolve method error in class android?

I use this tutorial: JSON and part of code to this: protected String doInBackground(String... urls) { TextView lbl=(TextView) findViewById(R.id.provCODE); person = new Person(); person.setName(lbl.getText().toString()); //person.setCountry("1853"); //person.setTwitter("1892"); return POST(urls[0],person); } but in the this line: person.setName(lbl.getText().toString()); i get this error: Can not resolve method. How can i solve that?what happen? my...

Uncaught error: Invalid type for google table column

I recently started using google visualization due to its simplicity. But while implementing in my recent project i seem to have run into a bit of trouble. The program shown is used to pull data from a JSON object and utilize it to display data in the google tables. Now...

Using .update with nested Serializer to post Image

I have an ImageField. When I update it with the .update command, it does not properly save. It validates, returns a successful save, and says it is good. However, the image is never saved (I don't see it in my /media like I do my other pictures), and when it...

Deserializing Json data to c# for use in GridView - Error Data source is an invalid type

I am relatively new to working with C# (v5.0) and Json data (Newtonsoft.Json v6.0) and am seeking assistance in resolving an error when attempting to populate a .Net 4.5 GridView control. My sample Json data as returned by a web service is: { PersonDetails: [ { Book: "10 ", FirstName:...

'utf8' codec can't decode byte 0xf3

I am using python 2.7 to read the json file. my code is import json from json import JSONDecoder import os path=os.path.dirname(os.path.abspath(__file__))+'/json' print path for root, dirs, files in os.walk(os.path.dirname(path+'/json')): for f in files: if f.lower().endswith((".json")): fp=open(root + '/'+f) data = fp.read() print data.decode('utf-8') But I got the following error....

How can i hook into django migrations for django 1.8

I am using django 1.8. Now i need to add some custom fields based permisions so i have created a YML file from python models like this description: permissions: ['ADMIN'] award: permissions: ['USER'] Its working fine but my issue if some chnages the field names or reomves some field then...

Django MySQLClient pip compile failure on Linux

Django documentation as of v1.8 recommends using mysqlclient connector for the framework. I'm attempting to pip install the package on Ubuntu 14.04 with Python 3.4 and running into a GCC error that I'm unable to find reference to. I'm not an expert on compiling software, so was hoping somebody can...

JQuery mutiple post in the same time

I have three functions ,and every function post to special php page to get data.. and every function need some time because every php script need some time .. function nb1() { $.post("p1.php", { action: 1 }, function(data) { console.log(data); }, "json") .fail(function(data) { console.log("error"); }); } function nb2() {...

Deserializing JSON into c# class

I have a JSON in the following format (from couchDB view) {"rows":[ {"key":["2015-04-01","524","http://www.sampleurl.com/"],"value":1}, {"key":["2015-04-01","524","http://www.sampleurl2.com/"],"value":2}, {"key":["2015-04-01","524","http://www.sampleurl3.com"],"value":1} ]} I need to create a "service" to get this data from couchDB and insert it on SQL Server (for generating reports..) in a efficient way. My first bet was to bulk insert this json...

Upload to absolute path in Django

I am trying to get upload_to of FileField to be an absolute path rather than relative to MEDIA_ROOT. If I make the path absolute I get a 400 error on post of file. If no leading / it stores under MEDIA_ROOT. The uploaded document needs to be held securely and...