Django, REST and Angular Routes

2019-01-30 16:36发布

问题:

I'm trying to wrap my head around combining a client-side framework like AngularJS with Django. One thing that's really confusing me is the issue of routes and REST.

I've been trying to read a lot about it online, but documentation is limited, especially in terms of Django being combined with Angular (little snippets here or there). I understand that I need to add a REST framework like TastyPie to make a robust REST interface in my app in order for Angular to plug in and grab resources.

However, I'm confused as to how to properly map out my routes in such a way that (1) my server-side app can render my single-page app (SPA) with angular plugged in (2) routes that are supposed to load information/render templates (angular) and retrieve data from the server (django) don't conflict. Like if I have someone going on my website and doing site.com/user/1234 - that route is associated with both the Angular route and the Django route - except one renders a template and the other spits out JSON based on what is retrieved from the DB/server.

In addition, by using the REST api, do I forego a lot of the advantages I have in terms of having ModelForms being synchronized with my Models, etc? Is there any way to maintain this with AngularJS or do I have to look towards an AngularJS substitute.

回答1:

The question isn't really specific to Django - just a matter of understanding the relationship between back-end and front-end in an SPA.

Routes are not duplicated between the back-end and the front-end. Your Django routes should be set up like:

/api/foo
/api/bar
...

and one single route that delivers a single page full of HTML partials, e.g.

/

The rest of the routes will be defined in Angular, e.g.

/articles/234
/blog/date/slug
...

The Angular controllers that handle those public-facing routes will in turn make $http calls against the API URLs and each will deliver one Angular partial. So there is no duplication, no overlap.

To the second part of your question, you can still use the Django ORM model relationships when constructing your API data, but yes, you'll lose all of that Django goodness when building the front-end.

If you build your API right, all of the data you need in each view will be fully present in the JSON feed that Angular consumes in that view. So you're using the ORM for back-end data construction, but you can't just decide to traverse a model relationship in a template without first preparing the back-end data to provide data for it.

Yes, it's a very different way of thinking of things, and yes it's quite a bit more complex than doing straight Django (or Rails). That's the cost of building a web app rather than a web site.