Home > Mobile >  Passing ID Mitch mech with Django Pattern in Axios, Vue JS
Passing ID Mitch mech with Django Pattern in Axios, Vue JS

Time:11-05

I am want to update and delete by clicking in Datatable button. But, unfortunately I could not passing the PK=ID in Django Pattern through Axios. enter image description here

`from django.urls import path
from . import views
from django.views.generic import TemplateView

app_name = 'todospaapp'

urlpatterns = [
    path('', views.index, name='index'),
    path('todos/', views.todos, name='todos'),
    path('save_todo/', views.save_todo, name='save_todo'),
    # path('<pk>/update', views.save_todo_update, name='save_todo_update' ),
    path('save_todo_update/<int:pk>', views.save_todo_update, name='save_todo_update'),
]`

In my view.py

`def save_todo_update(request, pk): try: todoitem = TodoItem.objects.get(pk=pk)

except TodoItem.DoesNotExist:
    return HttpResponse(status=404)

if request.method == 'GET':
    serializer = TodoItemSerializer(todoitem)
    return JsonResponse(serializer.data)

elif request.method == 'PUT':
    data = JSONParser.parse(request)
    serializer = TodoItemSerializer(todoitem, data=data)
    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data)
    return JsonResponse(serializer.errors)`

In my HTML:

<tbody>
            <tr v-for="todo in todos">
                <th scope="row" >[[todo.id]]</th>
                <td>[[todo.text]]</td>
                <td>[[todo.date_created | formatDate]]</td>
                <td>[[todo.date_completed | formatDate]]</td>
                <td><a class="btn btn-primary"  v-on:click="updateTodo(todo.id)" >Update</a></td>
            </tr>
        </tbody>

In Axios:

updateTodo: function(id) {
                axios({
                    url: "{% url 'todospaapp:save_todo_update/' id %}",
                    method: 'put',
                    data: {
                        todo_text: this.input_todo
                    },
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}'
                    }
                }).then(response => {
                    // console.log(response.data)
                    this.getTodos()
                })
            }
        },

CodePudding user response:

You can not work with a template tag to determine the URL since a template tag is resolved at the server, not at the client, and the JavaScript function runs at the client.

You thus should construct the url with:

axios({
    url: 'save_todo_update/'   id,
    # ⋮
}).then(response => {
    // console.log(response.data)
    this.getTodos()
})

CodePudding user response:

Change the url in html to:

    url: "{% url  'save_todo_update'  id %}",
               
  • Related