Django REST framework use AJAX url to point api detail url












0















I'm working on database program using Django. The program appends the database from user's forms/imported files, allows listing of data per category, and inline editing per category.



I did a lot of research (since i'm new in django), and so far I've been successful in generating forms, and and customized tables by combining rest framework and datatables.



The problem occurs when I tried to implement inline editing to my tables. I using the plugin datatables editor. My views and serializer seem to work since i can POST, PUT and DELETE in the Api Root. But then I can't make the ajax url point to the methods api detail views, I need the pkin the url to be variable to match the selection:



my serializer.py



class TankSerializer(serializers.ModelSerializer):
modified_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', input_formats=None)
updated_by = serializers.SlugRelatedField(slug_field='last_name', queryset=User.objects.all())
pid = serializers.SlugRelatedField(slug_field='number', queryset=PID.objects.all())
zone = serializers.SlugRelatedField(slug_field='number', queryset=ProcessZone.objects.all())
medium = serializers.SlugRelatedField(slug_field='code', queryset=Medium.objects.all())
revision = serializers.SlugRelatedField(slug_field='code', queryset=Revision.objects.all())
supplier = serializers.SlugRelatedField(slug_field='name', queryset=Supplier.objects.all())
po = serializers.SlugRelatedField(slug_field='number', queryset=PO.objects.all())
material = serializers.SlugRelatedField(slug_field='name', queryset=Material.objects.all())

DT_RowId = serializers.SerializerMethodField()

def get_DT_RowId(self, tank):
return 'row_%d' % tank.pk

class Meta:
model = Tank
fields = (
'DT_RowId', 'tag', 'description', 'pid', 'zone',
'medium', 'revision', 'supplier', 'po', 'material',
'volume', 'hight','modified_date','updated_by', 'created_by'
)


my views.py



@login_required
@ensure_csrf_cookie
def edit_tanks(request, project_code):
project = get_object_or_404(Project, code=project_code)
return render(request, 'edit_tanks.html', {'project': project})

class TankViewSet(viewsets.ModelViewSet):
queryset = Tank.objects.all().order_by('tag')
serializer_class = TankSerializer
lookup_filed = 'pk'

@action(methods=['get'], detail=True)
def get(self, request, pk, project_code, format=None):
serializer = self.serializer_class(self.queryset, many=True)
return Response(serializer.data)

@action(methods=['post'], detail=True)
def post(self, request, pk=None, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status.HTTP_201_CREATED)
return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

@action(methods=['patch'], detail=True)
def patch(self, request, pk, format=None):
queryset = self.get_object(pk)
serializer = self.serializer_class(queryset, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

@action(methods=['put'], detail=True)
def put(self, request, pk, format=None):
queryset = self.get_object(pk)
serializer = self.serializer_class(queryset, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

@action(methods=['delete'], detail=True)
def delete(self, request, pk, format=None):
queryset = self.get_object(pk)
queryset.delete()
return Response(status.HTTP_204_NO_CONTENT)


my urls.py



router = routers.DefaultRouter()
router.register(r'edit_tanks', views.TankViewSet, 'edit_tanks')

urlpatterns = [
re_path(r'^projects/(?P<project_code>d+)/engineering/equipment/edit_tanks/api/', include(router.urls)),
re_path(r'^projects/(?P<project_code>d+)/engineering/equipment/edit_tanks/$', views.edit_tanks, name='edit_tanks'),
path('admin/', admin.site.urls),
]


my template edit_tanks.html



{% block content %}
<div class="row">
<div class="col-sm-12">
<table id="edit_tanks" class="stripe row-border order-column" cellspacing="0" style="table-layout: auto; width:100%;">
<thead>
<tr>
<th></th>
<th>Tag</th>
<th>Description</th>
<th>PID</th>
<th>Zone</th>
<th>Medium</th>
<th>Revision</th>
<th>Supplier</th>
<th>PO</th>
<th>Material</th>
<th>Volume</th>
<th>Height</th>
<th>Last updated</th>
<th>Updated by</th>
</tr>
</thead>

</table>
</div>
</div>

{% endblock %}

{% block extra_js %}

<script type="text/javascript">


var editor;

$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {

ajax: {
create: {
type: 'POST',
url: 'api/edit_tanks/?format=datatables',
},
edit: {
type: 'PUT',
url: 'api/edit_tanks/{{tank_pk}}/',
},
remove: {
type: 'DELETE',
url: 'api/edit_tanks/{{tank_pk}}/',
}
},

table: "#edit_tanks",
fields: [ {
label: "Tag:",
name: "tag"
}, {
label: "Description:",
name: "description"
}, {
label: "Ravision:",
name: "revision.code",
type: "select"
}, {
label: "PO:",
name: "po.number",
type: "select"
},
]
} );

// Activate an inline edit on click of a table cell
$('#edit_tanks').on( 'click', 'tbody td:not(:first-child)', function (e) {
editor.inline( this );
} );

var table = $('#edit_tanks').DataTable({
"processing": true,
"serverSide": true,
ajax: {
url: "api/edit_tanks/?format=datatables",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}"
}
},
dom: 'Bfrtip',
language: {
search: "_INPUT_",
searchPlaceholder: "Search..."
},

"columns": [
{
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{"data": "tag"},
{"data": "description"},
{"data": "pid", "number": "pid.number"},
{"data": "zone", "number": "zone.number"},
{"data": "medium", "code": "medium.code"},
{"data": "revision", "code": "revision.code"},
{"data": "supplier", "name": "supplier.name"},
{"data": "po", "number": "po.number"},
{"data": "material", "name": "material.name"},
{"data": "volume"},
{"data": "hight"},
{"data": "modified_date"},
{"data": "updated_by", "last_name": "user.last_name"},
],
autoFill: {
columns: ':not(:first-child)',
editor: editor
},
keys: {
columns: ':not(:first-child)',
editor: editor
},
select: {
style: 'os',
selector: 'td:first-child',
blurable: true
},
buttons: [
{ extend: "create", editor: editor},
{ extend: "edit", editor: editor },
{
extend: "selected",
text: 'Duplicate',
action: function ( e, dt, node, config ) {
// Start in edit mode, and then change to create
editor
.edit( table.rows( {selected: true} ).indexes(), {
title: 'Duplicate record',
buttons: 'Create from existing'
} )
.mode( 'create' );
}
},
{ extend: "remove", editor: editor }
]
});

});

</script>
{% endblock %}


When I try edit or inline editing i get the




error 404 JSON: {"detail": "Not found."}




When i replace pk in the ajax url with a specific number, then i get




error 400




and JSON complains that all fields are required when they are not!



I've been stuck at this point for a while, and i can't find an answer that solves my problem.... any help would be appreciated!










share|improve this question



























    0















    I'm working on database program using Django. The program appends the database from user's forms/imported files, allows listing of data per category, and inline editing per category.



    I did a lot of research (since i'm new in django), and so far I've been successful in generating forms, and and customized tables by combining rest framework and datatables.



    The problem occurs when I tried to implement inline editing to my tables. I using the plugin datatables editor. My views and serializer seem to work since i can POST, PUT and DELETE in the Api Root. But then I can't make the ajax url point to the methods api detail views, I need the pkin the url to be variable to match the selection:



    my serializer.py



    class TankSerializer(serializers.ModelSerializer):
    modified_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', input_formats=None)
    updated_by = serializers.SlugRelatedField(slug_field='last_name', queryset=User.objects.all())
    pid = serializers.SlugRelatedField(slug_field='number', queryset=PID.objects.all())
    zone = serializers.SlugRelatedField(slug_field='number', queryset=ProcessZone.objects.all())
    medium = serializers.SlugRelatedField(slug_field='code', queryset=Medium.objects.all())
    revision = serializers.SlugRelatedField(slug_field='code', queryset=Revision.objects.all())
    supplier = serializers.SlugRelatedField(slug_field='name', queryset=Supplier.objects.all())
    po = serializers.SlugRelatedField(slug_field='number', queryset=PO.objects.all())
    material = serializers.SlugRelatedField(slug_field='name', queryset=Material.objects.all())

    DT_RowId = serializers.SerializerMethodField()

    def get_DT_RowId(self, tank):
    return 'row_%d' % tank.pk

    class Meta:
    model = Tank
    fields = (
    'DT_RowId', 'tag', 'description', 'pid', 'zone',
    'medium', 'revision', 'supplier', 'po', 'material',
    'volume', 'hight','modified_date','updated_by', 'created_by'
    )


    my views.py



    @login_required
    @ensure_csrf_cookie
    def edit_tanks(request, project_code):
    project = get_object_or_404(Project, code=project_code)
    return render(request, 'edit_tanks.html', {'project': project})

    class TankViewSet(viewsets.ModelViewSet):
    queryset = Tank.objects.all().order_by('tag')
    serializer_class = TankSerializer
    lookup_filed = 'pk'

    @action(methods=['get'], detail=True)
    def get(self, request, pk, project_code, format=None):
    serializer = self.serializer_class(self.queryset, many=True)
    return Response(serializer.data)

    @action(methods=['post'], detail=True)
    def post(self, request, pk=None, format=None):
    serializer = self.serializer_class(data=request.data)
    if serializer.is_valid():
    serializer.save()
    return Response(serializer.data, status.HTTP_201_CREATED)
    return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

    @action(methods=['patch'], detail=True)
    def patch(self, request, pk, format=None):
    queryset = self.get_object(pk)
    serializer = self.serializer_class(queryset, data=request.data, partial=True)
    if serializer.is_valid():
    serializer.save()
    return Response(serializer.data)
    return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

    @action(methods=['put'], detail=True)
    def put(self, request, pk, format=None):
    queryset = self.get_object(pk)
    serializer = self.serializer_class(queryset, data=request.data)
    if serializer.is_valid():
    serializer.save()
    return Response(serializer.data)
    return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

    @action(methods=['delete'], detail=True)
    def delete(self, request, pk, format=None):
    queryset = self.get_object(pk)
    queryset.delete()
    return Response(status.HTTP_204_NO_CONTENT)


    my urls.py



    router = routers.DefaultRouter()
    router.register(r'edit_tanks', views.TankViewSet, 'edit_tanks')

    urlpatterns = [
    re_path(r'^projects/(?P<project_code>d+)/engineering/equipment/edit_tanks/api/', include(router.urls)),
    re_path(r'^projects/(?P<project_code>d+)/engineering/equipment/edit_tanks/$', views.edit_tanks, name='edit_tanks'),
    path('admin/', admin.site.urls),
    ]


    my template edit_tanks.html



    {% block content %}
    <div class="row">
    <div class="col-sm-12">
    <table id="edit_tanks" class="stripe row-border order-column" cellspacing="0" style="table-layout: auto; width:100%;">
    <thead>
    <tr>
    <th></th>
    <th>Tag</th>
    <th>Description</th>
    <th>PID</th>
    <th>Zone</th>
    <th>Medium</th>
    <th>Revision</th>
    <th>Supplier</th>
    <th>PO</th>
    <th>Material</th>
    <th>Volume</th>
    <th>Height</th>
    <th>Last updated</th>
    <th>Updated by</th>
    </tr>
    </thead>

    </table>
    </div>
    </div>

    {% endblock %}

    {% block extra_js %}

    <script type="text/javascript">


    var editor;

    $(document).ready(function() {
    editor = new $.fn.dataTable.Editor( {

    ajax: {
    create: {
    type: 'POST',
    url: 'api/edit_tanks/?format=datatables',
    },
    edit: {
    type: 'PUT',
    url: 'api/edit_tanks/{{tank_pk}}/',
    },
    remove: {
    type: 'DELETE',
    url: 'api/edit_tanks/{{tank_pk}}/',
    }
    },

    table: "#edit_tanks",
    fields: [ {
    label: "Tag:",
    name: "tag"
    }, {
    label: "Description:",
    name: "description"
    }, {
    label: "Ravision:",
    name: "revision.code",
    type: "select"
    }, {
    label: "PO:",
    name: "po.number",
    type: "select"
    },
    ]
    } );

    // Activate an inline edit on click of a table cell
    $('#edit_tanks').on( 'click', 'tbody td:not(:first-child)', function (e) {
    editor.inline( this );
    } );

    var table = $('#edit_tanks').DataTable({
    "processing": true,
    "serverSide": true,
    ajax: {
    url: "api/edit_tanks/?format=datatables",
    data: {
    csrfmiddlewaretoken: "{{ csrf_token }}"
    }
    },
    dom: 'Bfrtip',
    language: {
    search: "_INPUT_",
    searchPlaceholder: "Search..."
    },

    "columns": [
    {
    data: null,
    defaultContent: '',
    className: 'select-checkbox',
    orderable: false
    },
    {"data": "tag"},
    {"data": "description"},
    {"data": "pid", "number": "pid.number"},
    {"data": "zone", "number": "zone.number"},
    {"data": "medium", "code": "medium.code"},
    {"data": "revision", "code": "revision.code"},
    {"data": "supplier", "name": "supplier.name"},
    {"data": "po", "number": "po.number"},
    {"data": "material", "name": "material.name"},
    {"data": "volume"},
    {"data": "hight"},
    {"data": "modified_date"},
    {"data": "updated_by", "last_name": "user.last_name"},
    ],
    autoFill: {
    columns: ':not(:first-child)',
    editor: editor
    },
    keys: {
    columns: ':not(:first-child)',
    editor: editor
    },
    select: {
    style: 'os',
    selector: 'td:first-child',
    blurable: true
    },
    buttons: [
    { extend: "create", editor: editor},
    { extend: "edit", editor: editor },
    {
    extend: "selected",
    text: 'Duplicate',
    action: function ( e, dt, node, config ) {
    // Start in edit mode, and then change to create
    editor
    .edit( table.rows( {selected: true} ).indexes(), {
    title: 'Duplicate record',
    buttons: 'Create from existing'
    } )
    .mode( 'create' );
    }
    },
    { extend: "remove", editor: editor }
    ]
    });

    });

    </script>
    {% endblock %}


    When I try edit or inline editing i get the




    error 404 JSON: {"detail": "Not found."}




    When i replace pk in the ajax url with a specific number, then i get




    error 400




    and JSON complains that all fields are required when they are not!



    I've been stuck at this point for a while, and i can't find an answer that solves my problem.... any help would be appreciated!










    share|improve this question

























      0












      0








      0








      I'm working on database program using Django. The program appends the database from user's forms/imported files, allows listing of data per category, and inline editing per category.



      I did a lot of research (since i'm new in django), and so far I've been successful in generating forms, and and customized tables by combining rest framework and datatables.



      The problem occurs when I tried to implement inline editing to my tables. I using the plugin datatables editor. My views and serializer seem to work since i can POST, PUT and DELETE in the Api Root. But then I can't make the ajax url point to the methods api detail views, I need the pkin the url to be variable to match the selection:



      my serializer.py



      class TankSerializer(serializers.ModelSerializer):
      modified_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', input_formats=None)
      updated_by = serializers.SlugRelatedField(slug_field='last_name', queryset=User.objects.all())
      pid = serializers.SlugRelatedField(slug_field='number', queryset=PID.objects.all())
      zone = serializers.SlugRelatedField(slug_field='number', queryset=ProcessZone.objects.all())
      medium = serializers.SlugRelatedField(slug_field='code', queryset=Medium.objects.all())
      revision = serializers.SlugRelatedField(slug_field='code', queryset=Revision.objects.all())
      supplier = serializers.SlugRelatedField(slug_field='name', queryset=Supplier.objects.all())
      po = serializers.SlugRelatedField(slug_field='number', queryset=PO.objects.all())
      material = serializers.SlugRelatedField(slug_field='name', queryset=Material.objects.all())

      DT_RowId = serializers.SerializerMethodField()

      def get_DT_RowId(self, tank):
      return 'row_%d' % tank.pk

      class Meta:
      model = Tank
      fields = (
      'DT_RowId', 'tag', 'description', 'pid', 'zone',
      'medium', 'revision', 'supplier', 'po', 'material',
      'volume', 'hight','modified_date','updated_by', 'created_by'
      )


      my views.py



      @login_required
      @ensure_csrf_cookie
      def edit_tanks(request, project_code):
      project = get_object_or_404(Project, code=project_code)
      return render(request, 'edit_tanks.html', {'project': project})

      class TankViewSet(viewsets.ModelViewSet):
      queryset = Tank.objects.all().order_by('tag')
      serializer_class = TankSerializer
      lookup_filed = 'pk'

      @action(methods=['get'], detail=True)
      def get(self, request, pk, project_code, format=None):
      serializer = self.serializer_class(self.queryset, many=True)
      return Response(serializer.data)

      @action(methods=['post'], detail=True)
      def post(self, request, pk=None, format=None):
      serializer = self.serializer_class(data=request.data)
      if serializer.is_valid():
      serializer.save()
      return Response(serializer.data, status.HTTP_201_CREATED)
      return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

      @action(methods=['patch'], detail=True)
      def patch(self, request, pk, format=None):
      queryset = self.get_object(pk)
      serializer = self.serializer_class(queryset, data=request.data, partial=True)
      if serializer.is_valid():
      serializer.save()
      return Response(serializer.data)
      return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

      @action(methods=['put'], detail=True)
      def put(self, request, pk, format=None):
      queryset = self.get_object(pk)
      serializer = self.serializer_class(queryset, data=request.data)
      if serializer.is_valid():
      serializer.save()
      return Response(serializer.data)
      return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

      @action(methods=['delete'], detail=True)
      def delete(self, request, pk, format=None):
      queryset = self.get_object(pk)
      queryset.delete()
      return Response(status.HTTP_204_NO_CONTENT)


      my urls.py



      router = routers.DefaultRouter()
      router.register(r'edit_tanks', views.TankViewSet, 'edit_tanks')

      urlpatterns = [
      re_path(r'^projects/(?P<project_code>d+)/engineering/equipment/edit_tanks/api/', include(router.urls)),
      re_path(r'^projects/(?P<project_code>d+)/engineering/equipment/edit_tanks/$', views.edit_tanks, name='edit_tanks'),
      path('admin/', admin.site.urls),
      ]


      my template edit_tanks.html



      {% block content %}
      <div class="row">
      <div class="col-sm-12">
      <table id="edit_tanks" class="stripe row-border order-column" cellspacing="0" style="table-layout: auto; width:100%;">
      <thead>
      <tr>
      <th></th>
      <th>Tag</th>
      <th>Description</th>
      <th>PID</th>
      <th>Zone</th>
      <th>Medium</th>
      <th>Revision</th>
      <th>Supplier</th>
      <th>PO</th>
      <th>Material</th>
      <th>Volume</th>
      <th>Height</th>
      <th>Last updated</th>
      <th>Updated by</th>
      </tr>
      </thead>

      </table>
      </div>
      </div>

      {% endblock %}

      {% block extra_js %}

      <script type="text/javascript">


      var editor;

      $(document).ready(function() {
      editor = new $.fn.dataTable.Editor( {

      ajax: {
      create: {
      type: 'POST',
      url: 'api/edit_tanks/?format=datatables',
      },
      edit: {
      type: 'PUT',
      url: 'api/edit_tanks/{{tank_pk}}/',
      },
      remove: {
      type: 'DELETE',
      url: 'api/edit_tanks/{{tank_pk}}/',
      }
      },

      table: "#edit_tanks",
      fields: [ {
      label: "Tag:",
      name: "tag"
      }, {
      label: "Description:",
      name: "description"
      }, {
      label: "Ravision:",
      name: "revision.code",
      type: "select"
      }, {
      label: "PO:",
      name: "po.number",
      type: "select"
      },
      ]
      } );

      // Activate an inline edit on click of a table cell
      $('#edit_tanks').on( 'click', 'tbody td:not(:first-child)', function (e) {
      editor.inline( this );
      } );

      var table = $('#edit_tanks').DataTable({
      "processing": true,
      "serverSide": true,
      ajax: {
      url: "api/edit_tanks/?format=datatables",
      data: {
      csrfmiddlewaretoken: "{{ csrf_token }}"
      }
      },
      dom: 'Bfrtip',
      language: {
      search: "_INPUT_",
      searchPlaceholder: "Search..."
      },

      "columns": [
      {
      data: null,
      defaultContent: '',
      className: 'select-checkbox',
      orderable: false
      },
      {"data": "tag"},
      {"data": "description"},
      {"data": "pid", "number": "pid.number"},
      {"data": "zone", "number": "zone.number"},
      {"data": "medium", "code": "medium.code"},
      {"data": "revision", "code": "revision.code"},
      {"data": "supplier", "name": "supplier.name"},
      {"data": "po", "number": "po.number"},
      {"data": "material", "name": "material.name"},
      {"data": "volume"},
      {"data": "hight"},
      {"data": "modified_date"},
      {"data": "updated_by", "last_name": "user.last_name"},
      ],
      autoFill: {
      columns: ':not(:first-child)',
      editor: editor
      },
      keys: {
      columns: ':not(:first-child)',
      editor: editor
      },
      select: {
      style: 'os',
      selector: 'td:first-child',
      blurable: true
      },
      buttons: [
      { extend: "create", editor: editor},
      { extend: "edit", editor: editor },
      {
      extend: "selected",
      text: 'Duplicate',
      action: function ( e, dt, node, config ) {
      // Start in edit mode, and then change to create
      editor
      .edit( table.rows( {selected: true} ).indexes(), {
      title: 'Duplicate record',
      buttons: 'Create from existing'
      } )
      .mode( 'create' );
      }
      },
      { extend: "remove", editor: editor }
      ]
      });

      });

      </script>
      {% endblock %}


      When I try edit or inline editing i get the




      error 404 JSON: {"detail": "Not found."}




      When i replace pk in the ajax url with a specific number, then i get




      error 400




      and JSON complains that all fields are required when they are not!



      I've been stuck at this point for a while, and i can't find an answer that solves my problem.... any help would be appreciated!










      share|improve this question














      I'm working on database program using Django. The program appends the database from user's forms/imported files, allows listing of data per category, and inline editing per category.



      I did a lot of research (since i'm new in django), and so far I've been successful in generating forms, and and customized tables by combining rest framework and datatables.



      The problem occurs when I tried to implement inline editing to my tables. I using the plugin datatables editor. My views and serializer seem to work since i can POST, PUT and DELETE in the Api Root. But then I can't make the ajax url point to the methods api detail views, I need the pkin the url to be variable to match the selection:



      my serializer.py



      class TankSerializer(serializers.ModelSerializer):
      modified_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', input_formats=None)
      updated_by = serializers.SlugRelatedField(slug_field='last_name', queryset=User.objects.all())
      pid = serializers.SlugRelatedField(slug_field='number', queryset=PID.objects.all())
      zone = serializers.SlugRelatedField(slug_field='number', queryset=ProcessZone.objects.all())
      medium = serializers.SlugRelatedField(slug_field='code', queryset=Medium.objects.all())
      revision = serializers.SlugRelatedField(slug_field='code', queryset=Revision.objects.all())
      supplier = serializers.SlugRelatedField(slug_field='name', queryset=Supplier.objects.all())
      po = serializers.SlugRelatedField(slug_field='number', queryset=PO.objects.all())
      material = serializers.SlugRelatedField(slug_field='name', queryset=Material.objects.all())

      DT_RowId = serializers.SerializerMethodField()

      def get_DT_RowId(self, tank):
      return 'row_%d' % tank.pk

      class Meta:
      model = Tank
      fields = (
      'DT_RowId', 'tag', 'description', 'pid', 'zone',
      'medium', 'revision', 'supplier', 'po', 'material',
      'volume', 'hight','modified_date','updated_by', 'created_by'
      )


      my views.py



      @login_required
      @ensure_csrf_cookie
      def edit_tanks(request, project_code):
      project = get_object_or_404(Project, code=project_code)
      return render(request, 'edit_tanks.html', {'project': project})

      class TankViewSet(viewsets.ModelViewSet):
      queryset = Tank.objects.all().order_by('tag')
      serializer_class = TankSerializer
      lookup_filed = 'pk'

      @action(methods=['get'], detail=True)
      def get(self, request, pk, project_code, format=None):
      serializer = self.serializer_class(self.queryset, many=True)
      return Response(serializer.data)

      @action(methods=['post'], detail=True)
      def post(self, request, pk=None, format=None):
      serializer = self.serializer_class(data=request.data)
      if serializer.is_valid():
      serializer.save()
      return Response(serializer.data, status.HTTP_201_CREATED)
      return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

      @action(methods=['patch'], detail=True)
      def patch(self, request, pk, format=None):
      queryset = self.get_object(pk)
      serializer = self.serializer_class(queryset, data=request.data, partial=True)
      if serializer.is_valid():
      serializer.save()
      return Response(serializer.data)
      return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

      @action(methods=['put'], detail=True)
      def put(self, request, pk, format=None):
      queryset = self.get_object(pk)
      serializer = self.serializer_class(queryset, data=request.data)
      if serializer.is_valid():
      serializer.save()
      return Response(serializer.data)
      return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)

      @action(methods=['delete'], detail=True)
      def delete(self, request, pk, format=None):
      queryset = self.get_object(pk)
      queryset.delete()
      return Response(status.HTTP_204_NO_CONTENT)


      my urls.py



      router = routers.DefaultRouter()
      router.register(r'edit_tanks', views.TankViewSet, 'edit_tanks')

      urlpatterns = [
      re_path(r'^projects/(?P<project_code>d+)/engineering/equipment/edit_tanks/api/', include(router.urls)),
      re_path(r'^projects/(?P<project_code>d+)/engineering/equipment/edit_tanks/$', views.edit_tanks, name='edit_tanks'),
      path('admin/', admin.site.urls),
      ]


      my template edit_tanks.html



      {% block content %}
      <div class="row">
      <div class="col-sm-12">
      <table id="edit_tanks" class="stripe row-border order-column" cellspacing="0" style="table-layout: auto; width:100%;">
      <thead>
      <tr>
      <th></th>
      <th>Tag</th>
      <th>Description</th>
      <th>PID</th>
      <th>Zone</th>
      <th>Medium</th>
      <th>Revision</th>
      <th>Supplier</th>
      <th>PO</th>
      <th>Material</th>
      <th>Volume</th>
      <th>Height</th>
      <th>Last updated</th>
      <th>Updated by</th>
      </tr>
      </thead>

      </table>
      </div>
      </div>

      {% endblock %}

      {% block extra_js %}

      <script type="text/javascript">


      var editor;

      $(document).ready(function() {
      editor = new $.fn.dataTable.Editor( {

      ajax: {
      create: {
      type: 'POST',
      url: 'api/edit_tanks/?format=datatables',
      },
      edit: {
      type: 'PUT',
      url: 'api/edit_tanks/{{tank_pk}}/',
      },
      remove: {
      type: 'DELETE',
      url: 'api/edit_tanks/{{tank_pk}}/',
      }
      },

      table: "#edit_tanks",
      fields: [ {
      label: "Tag:",
      name: "tag"
      }, {
      label: "Description:",
      name: "description"
      }, {
      label: "Ravision:",
      name: "revision.code",
      type: "select"
      }, {
      label: "PO:",
      name: "po.number",
      type: "select"
      },
      ]
      } );

      // Activate an inline edit on click of a table cell
      $('#edit_tanks').on( 'click', 'tbody td:not(:first-child)', function (e) {
      editor.inline( this );
      } );

      var table = $('#edit_tanks').DataTable({
      "processing": true,
      "serverSide": true,
      ajax: {
      url: "api/edit_tanks/?format=datatables",
      data: {
      csrfmiddlewaretoken: "{{ csrf_token }}"
      }
      },
      dom: 'Bfrtip',
      language: {
      search: "_INPUT_",
      searchPlaceholder: "Search..."
      },

      "columns": [
      {
      data: null,
      defaultContent: '',
      className: 'select-checkbox',
      orderable: false
      },
      {"data": "tag"},
      {"data": "description"},
      {"data": "pid", "number": "pid.number"},
      {"data": "zone", "number": "zone.number"},
      {"data": "medium", "code": "medium.code"},
      {"data": "revision", "code": "revision.code"},
      {"data": "supplier", "name": "supplier.name"},
      {"data": "po", "number": "po.number"},
      {"data": "material", "name": "material.name"},
      {"data": "volume"},
      {"data": "hight"},
      {"data": "modified_date"},
      {"data": "updated_by", "last_name": "user.last_name"},
      ],
      autoFill: {
      columns: ':not(:first-child)',
      editor: editor
      },
      keys: {
      columns: ':not(:first-child)',
      editor: editor
      },
      select: {
      style: 'os',
      selector: 'td:first-child',
      blurable: true
      },
      buttons: [
      { extend: "create", editor: editor},
      { extend: "edit", editor: editor },
      {
      extend: "selected",
      text: 'Duplicate',
      action: function ( e, dt, node, config ) {
      // Start in edit mode, and then change to create
      editor
      .edit( table.rows( {selected: true} ).indexes(), {
      title: 'Duplicate record',
      buttons: 'Create from existing'
      } )
      .mode( 'create' );
      }
      },
      { extend: "remove", editor: editor }
      ]
      });

      });

      </script>
      {% endblock %}


      When I try edit or inline editing i get the




      error 404 JSON: {"detail": "Not found."}




      When i replace pk in the ajax url with a specific number, then i get




      error 400




      and JSON complains that all fields are required when they are not!



      I've been stuck at this point for a while, and i can't find an answer that solves my problem.... any help would be appreciated!







      python ajax django datatables django-rest-framework






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jul 12 '18 at 10:40









      DamengeoDamengeo

      116




      116
























          1 Answer
          1






          active

          oldest

          votes


















          1














          This might help someone....



          In Datatables, when handling the CRUD methods on the Client-Side and using the Django Rest Framwork api, we need to point the right method to the right url, which means:




          • Use the "list url" for POST and GET a list (since we are not handing a single existing instance), so in my case the url would be url: 'api/edit_tanks/'

          • User the "detail url" for PUT, DELETE and GET an instance (need to pass the pk to identify the instance), in AJAX _id_ can be used to get the pk in the url. So my url would be : url: 'api/edit_tanks/_id_'


          This should solve the error:




          {"detail": "Not found."}




          For the "fields are required" error, make sure to specify in the serializer required=False in all the fields that are not required. I personally specify it in all fields and let the model handle the requirements.



          About the Views (API views):



          The ModelViewSet already includes all the CRUD methods, can always be overridden to add new parameters or own specific logic. My view becomes:



          class TankViewSet(viewsets.ModelViewSet):
          queryset = Tank.objects.all().order_by('tag')
          serializer_class = TankSerializer





          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51303537%2fdjango-rest-framework-use-ajax-url-to-point-api-detail-url%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            This might help someone....



            In Datatables, when handling the CRUD methods on the Client-Side and using the Django Rest Framwork api, we need to point the right method to the right url, which means:




            • Use the "list url" for POST and GET a list (since we are not handing a single existing instance), so in my case the url would be url: 'api/edit_tanks/'

            • User the "detail url" for PUT, DELETE and GET an instance (need to pass the pk to identify the instance), in AJAX _id_ can be used to get the pk in the url. So my url would be : url: 'api/edit_tanks/_id_'


            This should solve the error:




            {"detail": "Not found."}




            For the "fields are required" error, make sure to specify in the serializer required=False in all the fields that are not required. I personally specify it in all fields and let the model handle the requirements.



            About the Views (API views):



            The ModelViewSet already includes all the CRUD methods, can always be overridden to add new parameters or own specific logic. My view becomes:



            class TankViewSet(viewsets.ModelViewSet):
            queryset = Tank.objects.all().order_by('tag')
            serializer_class = TankSerializer





            share|improve this answer






























              1














              This might help someone....



              In Datatables, when handling the CRUD methods on the Client-Side and using the Django Rest Framwork api, we need to point the right method to the right url, which means:




              • Use the "list url" for POST and GET a list (since we are not handing a single existing instance), so in my case the url would be url: 'api/edit_tanks/'

              • User the "detail url" for PUT, DELETE and GET an instance (need to pass the pk to identify the instance), in AJAX _id_ can be used to get the pk in the url. So my url would be : url: 'api/edit_tanks/_id_'


              This should solve the error:




              {"detail": "Not found."}




              For the "fields are required" error, make sure to specify in the serializer required=False in all the fields that are not required. I personally specify it in all fields and let the model handle the requirements.



              About the Views (API views):



              The ModelViewSet already includes all the CRUD methods, can always be overridden to add new parameters or own specific logic. My view becomes:



              class TankViewSet(viewsets.ModelViewSet):
              queryset = Tank.objects.all().order_by('tag')
              serializer_class = TankSerializer





              share|improve this answer




























                1












                1








                1







                This might help someone....



                In Datatables, when handling the CRUD methods on the Client-Side and using the Django Rest Framwork api, we need to point the right method to the right url, which means:




                • Use the "list url" for POST and GET a list (since we are not handing a single existing instance), so in my case the url would be url: 'api/edit_tanks/'

                • User the "detail url" for PUT, DELETE and GET an instance (need to pass the pk to identify the instance), in AJAX _id_ can be used to get the pk in the url. So my url would be : url: 'api/edit_tanks/_id_'


                This should solve the error:




                {"detail": "Not found."}




                For the "fields are required" error, make sure to specify in the serializer required=False in all the fields that are not required. I personally specify it in all fields and let the model handle the requirements.



                About the Views (API views):



                The ModelViewSet already includes all the CRUD methods, can always be overridden to add new parameters or own specific logic. My view becomes:



                class TankViewSet(viewsets.ModelViewSet):
                queryset = Tank.objects.all().order_by('tag')
                serializer_class = TankSerializer





                share|improve this answer















                This might help someone....



                In Datatables, when handling the CRUD methods on the Client-Side and using the Django Rest Framwork api, we need to point the right method to the right url, which means:




                • Use the "list url" for POST and GET a list (since we are not handing a single existing instance), so in my case the url would be url: 'api/edit_tanks/'

                • User the "detail url" for PUT, DELETE and GET an instance (need to pass the pk to identify the instance), in AJAX _id_ can be used to get the pk in the url. So my url would be : url: 'api/edit_tanks/_id_'


                This should solve the error:




                {"detail": "Not found."}




                For the "fields are required" error, make sure to specify in the serializer required=False in all the fields that are not required. I personally specify it in all fields and let the model handle the requirements.



                About the Views (API views):



                The ModelViewSet already includes all the CRUD methods, can always be overridden to add new parameters or own specific logic. My view becomes:



                class TankViewSet(viewsets.ModelViewSet):
                queryset = Tank.objects.all().order_by('tag')
                serializer_class = TankSerializer






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 3 at 13:42

























                answered Jan 3 at 13:30









                DamengeoDamengeo

                116




                116
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51303537%2fdjango-rest-framework-use-ajax-url-to-point-api-detail-url%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Monofisismo

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas