[PYTHON] Django REST framework stumbling block

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']

URL mechanism

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},
        }

403 Forbidden (Cannot POST with JavaScript)

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>

JavaScript description

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

403 Forbidden (cannot be DELETE with JavaScript)

js-cookie See 403 Forbidden (Cannot POST with JavaScript)

JavaScript description

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

Django REST framework stumbling block
Django REST framework basics
Django Rest Framework Tips
Django REST framework with Vue.js
Login with django rest framework
[Django] Use MessagePack with Django REST framework
Create RESTful APIs with Django Rest Framework
Logical deletion in Django, DRF (Django REST Framework)
Understand the benefits of the Django Rest Framework
ng-admin + Django REST framework ready-to-create administration tool
CRUD GET with Nuxt & Django REST Framework ②
CRUD POST with Nuxt & Django REST Framework
CRUD GET with Nuxt & Django REST Framework ①
Django REST Framework + Clean Architecture Design Consideration
CRUD PUT, DELETE with Nuxt & Django REST Framework
Implement JWT login functionality in Django REST framework
Implementing authentication in Django REST Framework with djoser
Django python web framework
Create a Todo app with Django REST Framework + Angular
More new user authentication methods with Django REST Framework
Create a Todo app with the Django REST framework
Create APIs around user authentication with Django REST Framework
When you want to filter with Django REST framework
[Django Rest Framework] Customize the filter function using Django-Filter
Implement hierarchical URLs with drf-nested-routers in Django REST framework
How to write custom validations in the Django REST Framework
How to reset password via API using Django rest framework
Django rest framework decorators ʻaction decorator replaces list_route and detail_route`
Implementation of JWT authentication functionality in Django REST Framework using djoser
Implementation of CRUD using REST API with Python + Django Rest framework + igGrid
Create a REST API to operate dynamodb with the Django REST Framework
[Python] The stumbling block of import
Install Python framework django using pip
Implementation of custom user model authentication in Django REST Framework with djoser
How to deal with garbled characters in json of Django REST Framework
I made a webAPI! Build environment from Django Rest Framework 1 on EC2