search
LoginSignup
7

More than 3 years have passed since last update.

posted at

updated at

Django REST framework躓きどころ

Method Not Allowed:405

  • requestsのメソッド
    • postとputを間違えていた

401 Unauthorized

  • 権限をなくす設定
    • 'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.AllowAny']

URLの仕組み

  • GET: api/book/
  • POST: api/book/
  • PUT: api/book/1/

Serializer

  • fields = '__all__'を駆使する
  • 'required': Falseを駆使する
serializer.py
class HistorySerializer(serializers.ModelSerializer):
    class Meta:
        model = History
        fields = '__all__'
        extra_kwargs = {
            'id': {'required': False},
            'start_at': {'required': False},
        }

403 Forbidden (JavaScriptでPOSTできない)

js-cookie

以下ライブラリをインポートする
https://github.com/js-cookie/js-cookie/

例.

base.html
<script src="{% static 'js.cookie/js.cookie.min.js' %}"></script>

JavaScript記述

ajaxのパラメータに追加

js

params = {
    csrfmiddlewaretoken: Cookies.get('csrftoken'),
    ...
}
js
$('#btn-add-confirm').click(() => {
    let post_url = "/api/configs/";
    let params = {
        csrfmiddlewaretoken: Cookies.get('csrftoken'),  // こいつが必要
        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("ポストできませんでした");
        }
    });
})

403 Forbidden (JavaScriptでDELETEできない)

js-cookie

403 Forbidden (JavaScriptでPOSTできない) を参照

JavaScript記述

ajaxにbeforeSendを追加

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("ポストできませんでした");
        }
    });
})

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
7