Search code examples
djangoangularcsrfput

Send Angular PUT request to Django using Django CSRF


I am trying to update an entry into the django sqlite database using a put request. I am getting lots of 'forbidden' and '403' errors. I think this is because I can't find a way to attach the CSRF token from django.

I have seen some previous answers on here but they are from much older versions of Angular and I can't figure how to edit them to work with my code. (saying to put them in the module.config() block which I can't find).

Component HTML:

<button class="btn btn-warning shadow-sm" (click)="update(project)">Update</button>

Component TS:

update(project: Project) {
    this.projectService.updateProject(project).subscribe();
}

Service TS:

updateProject(project: Project) {
    var httpudpdate: any = this.http.put('/ph/projects/'+project.id, project)
    return httpudpdate
}

I want the entry to be updated in the django but I am just getting errors, forbidden and 403.


Solution

  • Just import HttpClientXsrfModule to your project, it will take care of reading the cookie and resending it as a custom header in every request.

    The cookie and header names are not a standard, but rather a convention, so you can configure them if the default ones don't match your backend's ones.

    As it happens, Django's cookie name and header name don't match Angular default ones so HttpClientXsrfModule has to be imported withOptions like this:

    import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http';
    
    @NgModule({
        ...
        imports:[..., HttpClientXsrfModule.withOptions({ cookieName: 'csrftoken', headerName: 'X-CSRFToken' }), ...]
        ...
    })