Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django with Angular 2

Tags:

angular

django

I want to integrate Angular 2 with Django and I have some questions to make.

  1. How can I change the interpolation syntax for Angular 2 from {{ }} to (( )) or something like this?

  2. How can I add the CSRF token from cookie to every HTTP post?

In Angular 1 I did something like this:

.config(function($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
  1. Is a good idea to integrate Angular 2 with Django?
like image 715
Rus Mine Avatar asked Jan 08 '16 08:01

Rus Mine


People also ask

Can I use Django with Angular?

Yes, creating API's using Django/DRF is sufficient to communicate with an Angular app. Below is an illustration of a basic architecture of a Django Angular application. API endpoints in Django will be served via the urls.py files using the DRF (Django Rest Framework.

Is Angular or Django better?

Angular vs Django: well, this depends upon the project you are working on. But the web development trends of 2022 indicate that Django and Angular both are going to be popular. Frankly, there will be no Django vs Angular. Both can be used together or separately if they fulfill the website or application requirements.

Is Django good for frontend?

“The technically correct answer,” Willison told me when I asked him about this, “is that a backend framework like Django works with any frontend framework, because of separation of concerns: if a web framework can respond to HTTP requests with JSON and HTML, it can be used with anything.”

What is the best frontend for Django?

React is best frontend library to work with django. react is easy to learn and implementing it with django is very easy.


3 Answers

I would recommend a different approach to the overall design of your Angular2-based project.

An Angular2-based application is meant to be used as a fully contained application running in the browser (similar conceptually to how a mobile application runs on a mobile OS). There should be a very clear and abrupt separation between your Angular2 app and the backend.

With that in mind, you can certainly use Django for your backend but not in the way a traditional Django app would use the framework with server-side rendered forms and pages.

Instead, you would rather design your backend so that it exposes a RESTful API interface with JSON payloads (with POST/PUT used to create and update objects, GET to fetch/list, etc.) Then your Angular2 app would consume that API to create the user-facing experience.

When submitted, an Angular2 form for creating an object would issue an HTTP POST request to your backend containing JSON-formatted data as its payload (and not the traditional form encoded data resulting from an HTML form submission)

Good tooling options for creating your RESTful backend API would be Django REST Framework or Tastypie.

For authentication, you could use JWT (JSON Web Tokens) and there are good add-ons for Django REST Framework that support that.

That architecture has one major advantage: in the future, if the evolution of your system requires real native mobile clients (Android or iOS apps for example), you should be able to consume the exact same RESTful API for those native apps.

That architecture also has drawbacks such as the inability to use Django forms-handling goodness out-of-the-box.

Considering the above, here are responses to your original questions:

  1. How can I change the interpolation syntax for angular2 from {{ }} to (()) or something like this.

There would be no need for that using the approach I suggest.

  1. How can i add the csrf token from cookie to every http post ?

If using JWT you would not need CSRF validation. If using session-based authentication, you would still need it but you could pass it using an HTTP header, as Langley suggested.

  1. Is a good ideea to integrate Angular2 with Django ?

Subjective but I would say yes, definitely. However, you need to make sure you clearly separate the backend from the frontend. The backend should not respond with server-side generated HTML snippets or HTML forms. That should all be handled within your Angular2 app.

like image 92
David M. Avatar answered Oct 09 '22 17:10

David M.


Hmm. All the three question I faced recently.

    1. Yes. It is definitely a great idea. Since you have the power of many python libraries as backend to perform whatever action you like combined with the power of angular. :D
    1. Works by injecting your own HTTP-Provider with Updated Default Request Options as Langley suggested. Edit: I recently found a nicer solution using angular2 cookie service. Which injects you CSRSFToken by providing a XSRFStrategy ;-)

A Drawback is that you require additional libs: NPM:Angular2-cookie

import { Injectable } from '@angular/core';
import { CookieService } from 'angular2-cookie/services/cookies.service';
import { HttpModule, Headers, BaseRequestOptions, RequestOptions, XSRFStrategy, CookieXSRFStrategy }    from '@angular/http';


@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions{
    headers:Headers = new Headers({
        'Content-Type': 'application/json'
    });
}

@NgModule({
    imports:  [...
        HttpModule],
    declarations: [
        AppComponent, ...,
    ],
    bootstrap: [AppComponent],
    providers: [...
        CookieService,
        {
            provide: RequestOptions,
            useClass: DefaultRequestOptions
        },
        {
            provide: XSRFStrategy,
            useFactory: (cookieService) => {
                return new CookieXSRFStrategy('csrftoken', 'X-CSRFToken');
            },
            deps: [CookieService]
        }
    ]
})
export class AppModule {
    constructor(){
       // ther you go ;-)
    }
}

static default Interpolation config within your '@angular/compiler' module.

import { DEFAULT_INTERPOLATION_CONFIG } from '@angular/compiler'

// These values will be used if not provided by your Component.interpolation

DEFAULT_INTERPOLATION_CONFIG.start = '{$';
DEFAULT_INTERPOLATION_CONFIG.end= '$}';
like image 21
tlausch Avatar answered Oct 09 '22 18:10

tlausch


There is a verbatim tag in Django ,
which can be used to ignore the {{}} tag inside verbatim block
Check here

like image 4
Anoop Ar Avatar answered Oct 09 '22 19:10

Anoop Ar