Method Not Allowed:405 --requests method --I made a mistake between post and put
401 Unauthorized --Setting to lose authority - 'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.AllowAny']
Serializer
--Use fields ='__all__'
--'required': Make full use of False
serializer.py
class HistorySerializer(serializers.ModelSerializer):
class Meta:
model = History
fields = '__all__'
extra_kwargs = {
'id': {'required': False},
'start_at': {'required': False},
}
js-cookie Import the following library https://github.com/js-cookie/js-cookie/
Example.
base.html
<script src="{% static 'js.cookie/js.cookie.min.js' %}"></script>
Added to ajax parameters
js
params = {
csrfmiddlewaretoken: Cookies.get('csrftoken'),
...
}
js
$('#btn-add-confirm').click(() => {
let post_url = "/api/configs/";
let params = {
csrfmiddlewaretoken: Cookies.get('csrftoken'), //I need this guy
year: $("#input-year").val(),
url: $("#input-url").val(),
num_of_report: 1,
is_selected: "0"
}
$.ajax({
url: post_url,
type: "POST",
data: params,
success: function(data, textStatus, jqXHR) {
window.location.reload();
},
error: function(jqXHR, textStatus, errorThrown) {
console.warn("Couldn't post");
}
});
})
https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
js-cookie See 403 Forbidden (Cannot POST with JavaScript)
Added beforeSend
to ajax
js
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", Cookies.get('csrftoken'));
},
js
$('.btn-delete').click(function() {
let post_url = "/api/configs/";
$.ajax({
url: post_url + $(this).val() + "/",
type: "DELETE",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", Cookies.get('csrftoken'));
},
success: function(data, textStatus, jqXHR) {
window.location.reload();
},
error: function(jqXHR, textStatus, errorThrown) {
console.warn("Couldn't post");
}
});
})
Recommended Posts