1,列表视图 class ArticlePostListView(ListView): model = ArticlePost context_object_name = 'post' template_name = 'course/course_list.html' # queryset = ArticlePost.objects.filter(user=User.objects.filter(username='admin')) #方法1 def get_queryset(self): #方法2 qs = super(ArticlePostListView,self).get_queryset() return qs.filter(user=User.objects.filter(username="admin")) 2,创建视图 class CreateArticlePostView(CreateView): #继承该类后不需要get方法 model = ArticlePost fields = ['title','body'] #对应form表单属性 template_name = 'course/manage/create_coruse.html' #模板文件 def post(self, request, *args, **kwargs): #重写Post方法 form = ArticlePostForm if form.is_valid(): new_post = form.save(commit=False) new_post.user = self.request.user new_post.save() return redirect("course:namege_course") return self.render_to_response({'form':form}) #如果前端不需要request属性,则可以使用render_to_response方法代替render方法 3,删除视图 class DeleteArticlePostView(DeleteView): model = ArticlePost # template_name = 'course/manage/delete_course_confirm.html' #原始方法,需要独立页面,不推荐 success_url = reverse_lazy("article:article_list") # reverse_lazy:当项目里的URLConf未加载时用来取代reverse。reverse_lasy是reverse的一层封装,这样我就可以用reverse_lazy可以用在任何reverse def dispatch(self, request, *args, **kwargs): resp = super(DeleteArticlePostView, self).dispatch(*args,**kwargs) if self.request.is_ajax(): #针对ajax方法优化处理 response_data = {"result":"ok"} return HttpResponse(json.dump(response_data,content_type="application/json")) else: return resp # url(r'dedete-course/(?P<pk>\d+/$)',DeleteArticlePostView.as_view(),name='delete_course') #只支持pk和slug关键字 # href={% url 'course:delete_course' course.id %}
django常用的通用视图方法
最新推荐文章于 2023-02-23 11:54:02 发布