N
N
nurzhannogerbek2017-08-15 13:50:39
Django
nurzhannogerbek, 2017-08-15 13:50:39

How to properly rewrite FBV to CBV in Django?

Hello! Please help me understand the Class Based View.
How to take a specific object in CBV? I have a working Function Based View. I'm trying to rewrite it on CBV, but some places do not fit in my head. For example, in FBV you specify pk in the arguments and then you already take a specific object by this primary key book = get_object_or_404(Book, pk=pk). How to implement it in CBV? Please help me figure it out. I would be grateful for any help!
FBV:

def book_delete(request, pk):
    book = get_object_or_404(Book, pk=pk)
    data = dict()
    if request.method == 'POST':
        book.delete()
        data['form_is_valid'] = True
        books = Book.objects.all()
        data['html_book_list'] = render_to_string('books.html', {
            'books': books
        })
    else:
        context = {'book': book}
        data['html_form'] = render_to_string('book_delete.html',
            context,
            request=request,
        )
    return JsonResponse(data)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nurzhannogerbek, 2017-08-16
@nurzhannogerbek

The CBV for the above FBV article would be the following:

class BookDeleteView(View):
    def post(self, request, pk, *args, **kwargs):
        data = dict()
        book = Book.objects.get(pk=pk)
        book.delete()
        data['form_is_valid'] = True
        context = {
            'books': Book.objects.all()
        }
        data['html_books'] = render_to_string(
            'books.html',
            context
        )
        return JsonResponse(data)

    def get(self, request, pk, *args, **kwargs):
        data = dict()
        book = Book.objects.get(pk=pk)
        context = {
            'book': book
        }
        data['html_book_delete_form'] = render_to_string(
            'delete_book.html',
            context,
            request=request,
        )
        return JsonResponse(data)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question