是的,可以将djangoTutorial中的polls教程中的函数视图(FBV)转换为类视图(CBV)。类视图是基于类的视图,可以提供更多的功能和灵活性。
要将FBV转换为CBV,可以按照以下步骤进行操作:
ListView
、DetailView
、CreateView
等,具体取决于你的需求。get()
方法和一个post()
方法,你可以将它们分别移动到类视图的get()
和post()
方法中。put()
、delete()
等,以支持其他HTTP请求方法。as_view()
方法将类视图转换为可用于URL配置的可调用对象。下面是一个示例,演示如何将polls
应用程序中的vote
函数视图转换为类视图:
from django.views import View
from django.shortcuts import get_object_or_404, render
from .models import Question
class VoteView(View):
def get(self, request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def post(self, request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
在URL配置中,你可以将原始的函数视图替换为新的类视图:
from django.urls import path
from .views import VoteView
app_name = 'polls'
urlpatterns = [
# ...
path('<int:question_id>/vote/', VoteView.as_view(), name='vote'),
# ...
]
这样,你就成功将vote
函数视图转换为VoteView
类视图。
请注意,上述示例中的代码仅用于演示目的,实际情况下可能需要根据你的具体需求进行调整和修改。
关于Django的类视图和通用视图的更多信息,请参考Django官方文档。
领取专属 10元无门槛券
手把手带您无忧上云