多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
>[success] # CBV 编写 url 用 as_view() ~~~ urlpatterns = [ # url(r'^$', views.index, name='index'), url(r'^$', views.IndexView.as_view(), name="index") ] ~~~ 类一定要继承否则报错 ~~~ from django.views import View class IndexView(View) ~~~ >[danger] ##### 小技巧 ~~~ 1.引用类的时候遵循最上面是django 的类 ,第二层系统自带类,第三层自定义的类 2.CBV 中的结构 * 一个全局变量 template_name 用来方网页名字的 * 一个存储数据的方法 get_context(self) * 对响应请求添加 用updata 加入字典中 ~~~ >[danger] ##### 写法 ~~~ class IndexView(View): template_name = 'index.html' def get_context(self): students = models.Student.objects.all() context = { 'students': students, } return context def get(self,request): context = self.get_context() form = forms.StudentForm() # 把后续需要添加的变量加入 context.update({ 'form':form, }) return render(request, self.template_name, context=context) def post(self,request): form = forms.StudentForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data student = models.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 redirect(reverse('index')) context = self.get_context() context.update({ 'form':form, }) return render(request, self.template_name, context=context) ~~~