R
R
Radiss2020-05-08 23:11:05
Django
Radiss, 2020-05-08 23:11:05

Django. How to implement delete class in class based views?

Application with a choice of tasks. When you select one of the items, deletion should occur.

In functions, it looked through complete_task

views.py

spoiler

from django.http import HttpResponse
from django.shortcuts import redirect, render
from tasks.models import TodoItem
from tasks.models import TodoItemForm


def index(request):
    return HttpResponse("Примитивный ответ из приложения tasks")


def complete_task(request, uid):
    print(uid)
    return HttpResponse("OK")


def delete_task(request, uid):
    print(uid)
    return redirect("/tasks/list")

# Сервер включает обработчик для этого адреса (функция task_create в
# модуле tasks.views). В шаблоне отображается ("рендерится") форма, при этом
#  заодно создаётся CSRF-токен


def task_create(request):
    if request.method == "POST":
        form = TodoItemForm(request.POST)
        if form.is_valid():
            form.save()
        return redirect("/tasks/list")
    else:
        form = TodoItemForm()
    return render(request, "tasks/create.html", {"form": form})


def tasks_list(request):
    all_tasks = TodoItem.objects.all()
    return render(
        request,
        'tasks/list.html',
        {'tasks': all_tasks}
    )


# В обработчике tasks.views.add_task мы проверяем, что к нам пришёл и правда
# POST запрос, вычленяем из него то, что было заполнено в поле для
# description и создаём TodoItem для этой задачи.

def add_task(request):
    if request.method == "POST":
        desc = request.POST["description"]
        t = TodoItem(description=desc)
        t.save()
    return redirect("/tasks/list")
# ...



url.py

spoiler

from django.urls import path

from . import views


urlpatterns = [
    path('', views.index, name='index'),
    path('list/', views.tasks_list, name='list'),
    path("create/", views.task_create, name="create"),
    path("add-task/", views.add_task, name="api-add-task"),
    path('complete/<int:uid>', views.complete_task, name='complete'),
    path('delete/<int:uid>', views.delete_task, name='delete'),
]



Only task creation works with classes

spoiler

from django.http import HttpResponse
from django.shortcuts import redirect, render
from tasks.models import TodoItem
from tasks.models import TodoItemForm
from django.views import View
from django.views.generic import ListView
from django.views.generic.edit import DeleteView, UpdateView


def index(request):
    return HttpResponse("Примитивный ответ из приложения tasks")


class TaskCompleteView(UpdateView):
    def get(self, request, *args, **kwargs):
        form = TodoItemForm()
        return render(request, "tasks/list.html", {"form": form})


class TaskDeleteView(DeleteView):
    def my_render(self, request, form):
        return render(request, "tasks/delete.html", {"form": form})

    def get(self, request, *args, **kwargs):
        form = TodoItemForm()
        return render(request, "tasks/delete.html", {"form": form})


class TaskListView(ListView):
    queryset = TodoItem.objects.all()
    context_object_name = "tasks"
    template_name = "tasks/list.html"


class TaskCreateView(View):
    def my_render(self, request, form):
        return render(request, "tasks/create.html", {"form": form})

    def post(self, request, *args, **kwargs):
        form = TodoItemForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/tasks/list")

        return render(request, "tasks/create.html", {"form": form})

    def get(self, request, *args, **kwargs):
        form = TodoItemForm()
        return render(request, "tasks/create.html", {"form": form})



urls.py

spoiler

from django.urls import path

from . import views


urlpatterns = [
    path("", views.index, name="index"),
    path("list/", views.TaskListView.as_view(), name="list"),
    path("create/", views.TaskCreateView.as_view(), name="create"),
    path("complete/", views.TaskCompleteView.as_view(), name="complete"),
    path("delete/", views.TaskDeleteView.as_view(), name="delete"),
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tema_sun, 2020-05-08
@tema_sun

Try this:
views.py

...
class TaskDeleteView(DeleteView):
    model = TodoItem
...

urls.py
...
path("delete/<int:pk>", views.TaskDeleteView.as_view(), name="delete"),
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question