Method Not Allowed:405
401 Unauthorized
Serializer
--Utilisez fields = '__ all __' ' --
'required ': utiliser pleinement False`
serializer.py
class HistorySerializer(serializers.ModelSerializer):
class Meta:
model = History
fields = '__all__'
extra_kwargs = {
'id': {'required': False},
'start_at': {'required': False},
}
js-cookie Importez la bibliothèque suivante https://github.com/js-cookie/js-cookie/
Exemple.
base.html
<script src="{% static 'js.cookie/js.cookie.min.js' %}"></script>
Ajouté aux paramètres ajax
js
params = {
csrfmiddlewaretoken: Cookies.get('csrftoken'),
...
}
js
$('#btn-add-confirm').click(() => {
let post_url = "/api/configs/";
let params = {
csrfmiddlewaretoken: Cookies.get('csrftoken'), //J'ai besoin de ce gars
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("Impossible de publier");
}
});
})
https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
js-cookie Voir 403 Interdit (impossible de POST avec JavaScript)
Ajout de beforeSend
à 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("Impossible de publier");
}
});
})
Recommended Posts