1

Edit: I'm using Django dev version so I do have access to JsonResponse (as seen below).

I'm messing around with Django and trying to make it work with AngularJS. Currently I'm attempting to query 4 rows from a database at a time and send the results as a JSON object to an Angular script. I just keep running into issues though - it won't work.

Here's where my code is at right now after a bunch of searching on StackOverflow to try and help myself out:

# views.py

class AJAXListMixin(object):
    def dispatch(self, request, *args, **kwargs):
        if not request.is_ajax():
            raise Http404("Improper access.")
        return super(object, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        return Project.objects.filter(added__lte=timezone.now())

    def get(self, request, *args, **kwargs):
        return JsonResponse(self.get_queryset(), safe=False)


class PageApi(AJAXListMixin, generic.ListView):
    paginate_by = 4  # 4 results per page
    ordering = '-added'  # Most recent to oldest

----------------------
# models.py

class Project(models.Model):
    title = models.CharField(max_length=100)
    desc = models.TextField()
    link = models.URLField(default=None, blank=True, null=True)

    slug = models.SlugField(null=True)
    added = models.DateField(_("Date Added"), default=datetime.today)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Project, self).save(*args, **kwargs)

    def as_dict(self):
        return {
            "title": self.title,
            "description": self.desc,
            "link": self.link,
            "slug": self.slug,
            "date": self.added,
            "previews": {
                preview.as_dict() for preview in self.preview_set.all()
            }
        }


class Preview(models.Model):
    project = models.ForeignKey(Project)
    file = models.FileField(upload_to='project/preview/')

    def __str__(self):
        return "{project} Preview {id}".format(
            project=self.project.title, id=self.id
        )

    def as_dict(self):
        return {
            "url": self.file.url
        }

And here is the angular code I'm starting off with:

projects = angular.module("Projects", []);

projects.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
}]);

projects.controller("ProjectList", ['$scope', '$http', function ($scope, $http) {
  $scope.projects = {};
  $scope.page = 1;

  $http.get('api/page/' + $scope.page)
      .success(function (response) {
        console.log(response)
      })
      .error(function (status) {
        alert("Error. Check network logs.");
      });
}]);

I want to store the response in the projects $scope variable so that I can do things with the data in my angular template.

1 Answer 1

4

I'd recommend taking a look the following post:

http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html or this one https://thinkster.io/django-angularjs-tutorial/

It walks through setting up a REST API in Django to serialize your models, and specifying which fields are to serialized and returning JSON data using the Django Rest Framework.

Note that the example uses CoffeeScript and compiles it into JavaScript using GruntJS.

Instead your Angular controller should look more like the following (assuming you have a URL '/api/projects/', that routes to an API view that returns a JSON object containing multiple projects):

$scope.projects = [];
$http.get('/api/projects/').success(function(data) {
    $scope.projects = data;
    console.log($scope.projects);

});

Not sure how this would work with the additional pagination, but you can read more about it on the Django Rest Framework docs:

http://www.django-rest-framework.org/api-guide/pagination/

Hope this helps!

Sign up to request clarification or add additional context in comments.

5 Comments

I'm a little lost on how to create my serializers to access the preview images I want. I don't currently have a url path to view preview images separately from the projects they're associated with. Is there a way to set up the serializers to get the url to the images without having to set up routes? See pastebin.com/AaVzGyer
How is Preview associated with Project?
A Project has one or more Preview images. Each image (Preview) is a single upload from the admin interface on a Project entry.
Snig501, you can look here for a bit more detail: reddit.com/r/django/comments/2o87mq/…
Does the following help any? django-rest-framework.org/api-guide/relations/… (Sorry, I'm at work at the moment so I can't offer a huge amount of assistance at the moment - i.e. I can't test this myself :P)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.