Class Based View(基于类的通用视图)
使用类视图可以减少视图函数的重复代码,节省开发时间,这里使用Class Based View主要是分离get和post请求
重新修改views.py
from __future__ import unicode_literals
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import render
from django.views import View
from .models import Student
from .forms import StudentForm
class IndexView(View):
template_name = 'index.html'
def get_context(self):
students = Student.objects.all()
context = {
'students': students,
}
return context
def get(self, request):
context = self.get_context()
form = StudentForm()
context.update({
'form': form,
})
return render(request, self.template_name, context=context)
def post(self, request):
form = StudentForm(request.POST)
if form.is_valid():
cleaned_data = form.cleaned_data
student = Student()
student.name = cleaned_data['name']
student.sex = cleaned_data['sex']
student.email = cleaned_data['email']
student.profession = cleaned_data['profession']
student.qq = cleaned_data['qq']
student.phone = cleaned_data['phone']
student.save()
return HttpResponseRedirect(reverse('index'))
context = self.get_context()
context.update({
'form': form,
})
return render(request, self.template_name, context=context)
接下来修改django_student/urls.py,as_view()将类视图转换成函数视图,之前的index就是视图函数
urlpatterns = [
url(r'^$', IndexView.as_view(), name='index'),
url(r'^admin/', admin.site.urls),
]