我正在关注本教程about ajax and crud。本教程使用基于函数的视图方法,相反,我想使用基于类的视图,特别是对于此视图。
def book_create(request):
data = dict()
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
form.save()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
data['form_is_valid'] = False
else:
form = BookForm()
context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
context,
request=request
)
return JsonResponse(data)
答案 0 :(得分:0)
这是基于您的案例的基于类的视图的示例。
from django.views import View
class BookCreateView(View):
def post(self, request):
form = BookForm(request.POST)
if form.is_valid():
form.save()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
context,
request=request
)
return JsonResponse(data)
def get(self, request):
data = dict()
form = BookForm()
context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
context,
request=request
)
return JsonResponse(data)