Reputation: 5366
I have a project where my Rest API is written in django rest framework serving JSON and my frontend is totally separate (it's a whole different project created through yeomann, this also could be an Ionic app) angular2 app which basically consumes that json data.
What is the cleanest way of handling forms in this scenario? Can someone give me sample simple code snippets?
My angular app will have a form and on submit it will hit a url defined in my Django backend that processes that POST request and saves a specific new model instance (i.e. Angular2 form to add new book and django view that saves a new book according to the data provided by the user in angular2 form)
How can it be done? My angular app will not have any django tags like these {% extends 'blog/base.html' %}
nor my django app will have any templates, it is a pure rest API.
Upvotes: 0
Views: 1800
Reputation: 43
I assume that you've already got the form component in your app. Then, to send data to API, you need to do the following:
Create a JS class with same fields as your model in Django has. For example:
export class Book {
name: string;
description: string;
}
Create an instance of this class in your form component and connect its attributes to form fields. Example:
export class BookFormComponent implements OnInit {
constructor(private _bookService: BookService) {}
// ...
book: Book = new Book();
}
Also I've shown the constructor here to show that we are connecting to EventsService, which is responsible for communication with API.
In template: bind your inputs to your object attributes (see Angular guide to forms):
<form (ngSubmit)="onSubmit()" #bookForm="ngForm" id="bookForm">
<label for="bookName">Book name:</label>
<input type="text" name="name" id="bookName" maxlength="140"
required [(ngModel)]="book.name"/>
<label for="bookDescription">Description:</label>
<textarea form="bookForm" name="description" id="bookDescription" rows="3"
required [(ngModel)]="book.description"></textarea>
</form>
Create a method in your service which will send a POST
request. It may look like this:
export class BookService {
_bookUrl = 'http://your.api.url/books-view'
addBook(book: Book) {
let headers = new Headers();
headers.append('Content-Type','application/json');
headers.append('X-CSRFToken', this.getCookie('csrftoken'));
return this.http.post(this._booksUrl, JSON.stringify(book),
{headers: headers})
.toPromise()
.then(res => res.json())
.catch(this.handleError);
}
}
_booksUrl
is a URL of your view with list of books in Django REST Framework.
You may have problems with API not saving data because of you not being logged in. Adding Headers as seen above is the easiest workaround, but I suggest you to look for other options to authorize.
Call addBook() from your service in onSubmit inside the component:
onSubmit() {
this.addBook(this.book);
}
addBook(book: Book) {
let res = this._bookService.addBook(book)
.then(
result => res = result);
}
After those steps your Angular app should communicate with your Django REST API with no problems.
This is a simplified version of the project I'm doing. You may check the code on github (see event-form.component.ts
and events.service.ts
) to see the whole picture.
Upvotes: 4