Skip to content

Iron-Ajax POST method CSRF Error in Django #301

@michael-learns

Description

@michael-learns

Description

I'm using Polymer 2.0 web components on my Django Project. I needed to make a POST request to my views.py but I'm getting a 403 Error (Forbidden) because my CSRF token was missing or incorrect.

Expected outcome

I should be able to see the body of my request in my views.py

Actual outcome

A CSRF error occurs.

Here's a sample code of my custom-element:

`

	<iron-ajax 
		id="requestAjax"
		auto="false"
		url='/delete_credits_submission/'
		body="{{body}}"
		method="POST"
		handle-as="json"
		content-type="application/json"
		on-response="_showResponse"></iron-ajax>

	<template is="dom-repeat" items="[[response]]" as="item">
		<paper-card heading=[[item.name]] image="" elevation="1" animated-shadow="false">
			<div class="card-content">
				<paper-input value=[[item.age]] label="Age"></paper-input>
				<paper-input value=[[item.credits]] label="Credits"></paper-input>
			</div>
			<div class="card-actions">
				<paper-button raised on-tap="_deleteCard">Delete</paper-button>
			</div>
		</paper-card>
	</template>
</template>

<script>
    class CardList extends Polymer.Element {
        static get is() { return 'cards-list'; }
        static get properties() {
            return { 
				response : {
					// observer: '_showResults',
					type: Array
				},
				auto: {
					type: String
				},
				cardID: {
					type: Number,
					notify: true
				},
				body: {
					type: Object,
					notify: true
				}
            }
        }
        constructor() {
            super()
        }

		// _showResults() {
		// 	console.log(this.response)
		// }

		_showResponse(event, request) {
			console.log(event);
		}

		_callRequest() {
			this.response = this.$.ironAjax.generateRequest();
		}

		_deleteCard(e) {
			this.cardID = e.model.item.id;
			this.body = {'pk' : this.cardID};
			console.log(this.body)
			this.$.requestAjax.generateRequest();
		}

    }

    window.customElements.define(CardList.is, CardList);
</script>

`

Here's a sample of my views.py for the /delete_credits_submission/ url

"""Note that my request.POST or request.GET should contain this object:
{'pk': 4}
"""
def delete_credits_submission(request): print request.GET return HttpResponse('Success!', status=200)

Instead I'm getting this error:

Forbidden (CSRF token missing or incorrect.): /delete_credits_submission/

Usually, when I'm using the Django templates I can easily fix this problem using {% csrf_token %} but that's not the case here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions