Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    })

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.

update

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": [
                {
                    "id":5
                    "name": "Bloom",
                    "very_important": True,
                    "finished": False
                },
                {
                    "id":4
                    "name": "REST",
                    "very_important": True,
                    "finished": True
                }
            ]
        },
        {
            "id": 2,
            "date": "2015-06-22",
            "day_todo_set": [
                {
                    "id":3
                    "name": "Alarm 1",
                    "very_important": True,
                    "finished": True
                },
                {
                    "id":2
                    "name": "Meet up with SIS",
                    "very_important": True,
                    "finished": False
                },
                {
                    "id":1
                    "name": "Buy Milk",
                    "very_important": True,
                    "finished": False
                }
            ]
        }
    ]
    
  2. Manipulate objects

js:

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

    $.ajax({
        type: 'GET',
        url: '/api/.json',
        success: function(days) {
            $.each(days, function(i, day) {
                $days.append('<li>date: '+ day.date+ '</li>')
            });
        }
    });
})
like image 843
Kakar Avatar asked Jun 23 '15 08:06

Kakar


2 Answers

model.py:

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.

@csrf_exempt
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')
like image 190
RéÑjïth Avatar answered Oct 23 '22 01:10

RéÑjïth


rest framework is not aimed to serve html that is displayed in a browser. It is aimed to serve data to another service (a mobile device, an heavy client, an other server, etc.)

First line of the documentation:

Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.

If you want to display the result in a browser, use templates and do not use rest

like image 3
Sylvain Biehler Avatar answered Oct 23 '22 01:10

Sylvain Biehler