Added by: Sam Deering
Django is used to provide the API and for its admin.
It's assumed you have Python and Postgres already installed.
pip install -r requirements.txt
python manage.py syncdb --migrate
python -m SimpleHTTPServer. You should create a serve.bat file for this. This is the Angular app.
python managae runserver 0.0.0.0:8001I created a batch file for this called r.bat. This is your API and admin.
Now we have the admin and front-end client both running. Let's test.
You will get a "missing key" error message. This is because your user does not have API access. To add access, go to http://localhost:8001/admin/tastypie/apikey/add/ and add a key. Any key will do. You can have this key added automatically for new users by uncommenting out the signal at the bottom of myproperty/models.py.
Go back and try to login again. This time, your login worked! Find your just added data at http://localhost:8001/admin/myproperty/paymenttype/.
If you take a look at js/controllers.js, you'll find the
ContentController. When you submit the form, it's trying to post to [http://localhost:8001/api/myproperty/paymenttype/]. However, it gets a 401 status code back because you're not logged in.
Tastypie is requiring authentication for this resource in ch/api.py by using the ApiKeyAuthentication class in PaymentTypeResource.
This TastyPie class looks for the API key in the GET/POST or header. We are using headers. On login, we set the header within Angular.js. See js/controllers.js ~ line 27
$http.defaults.headers.common['Authorization'] = 'ApiKey ' + data.username + ':' + data.key;
Because Django returns a status code 401, Angular intercepts this (lib/http-auth-interceptor.js ~line 61) and instead displays the login screen. Once you have a valid API key, it replays your API call and continues where it left off.
This is a very basic demo. I hope it helps shortcut getting you started with AngularJS and Django. You might want to add additional checking in your TastyPie authentication so that the API key expires after a certain amount of time, or even if the IP changes.
Module stats last updated: 2017-10-01 16:00:05