I'm new to AngularJs and I'm trying to make an AngularJS application that consumes JSON from a Django Rest framework api , and I have been advised to seperate the project into 2 seperate apps one for Django and an othet for AngularJS (even using 2 different IDEs) , my question is how can I set up my AngularJS app and my Django app so they can communicate with each other knowing that I'm working on localhost ? How will Django Rest framework respond to the AngularJS requests ? Thank you
-
You want to run 2 applications on the same port/url or you want to separate them?zymud– zymud2015-07-08 18:00:36 +00:00Commented Jul 8, 2015 at 18:00
-
I would like for AngularJs to run on the client side and Django on the server side , however didn't exactly figure out what type of configuration I need in order for them to communicate . I set up CORS in Rest Framework and still looking what to do from Angular's sidebalance– balance2015-07-09 11:59:04 +00:00Commented Jul 9, 2015 at 11:59
1 Answer
The simple way is to have a Django template view serving your client (AngularJS) application.
Another would be to use NodeJS + Express + Grunt/Gulp to serve the client application on another port on localhost and set up CORS in Rest Framework.
Either way you'll then do $http.get/post/whatever calls to the Django host:port app from the client application.
I usually use the second approach.
views.py
class HomePageView(TemplateView):
template_name = 'home.html'
urls.py*
urlpatterns = patterns('public.views',
url(r'^$', HomePageView.as_view(), name='home'),
templates/home.html
<!DOCTYPE html>
{% load i18n %}
{% load staticfiles %}
{% load compress %}
<html lang="en">
<head>
<meta charset="utf-8"/>
...
{% compress css %}
<link rel="stylesheet" href="{% static "libs/bootstrap/css/bootstrap.css" %}">
...
{% endcompress %}
</head>
<body ng-app="MyApp">
...
{% compress js %}
<script src="{% static "libs/jquery/jquery.js" %}"></script>
...
<script src="{% static "js/my-app/controllers/my-controller.js" %}"></script>
....
{% endcompress %}
</body>
For the AngularJS part I use Gulp, Browserify and a lot of other stuff. Please take that boilerplate with a grain of salt, I came up with that for a very specific set of reasons.