是.您缺少函数调用:
url(r'^add_category/', views.CategoryCreateView.as_view(), name='add-category'),
至于你的其他问题,CreateView
并且FormView
非常相似,除了CreateView
更具体的实现FormView
.
FormView
真的是要处理:
在GET上显示表格
显示POST时出错的表单
当表单没有错误时,重定向到不同的页面
CreateView
另一方面,FormView
除了这样做之外,它是相同的:
假设它正在处理一个ModelForm
实现save()
方法的表单
在重定向到不同的页面之前,save()
会调用表单来创建模型
存储创建的模型,self.object
以便您可以使用它get_success_url
来为创建的对象生成URL(例如,重定向到对象详细信息页面)
优雅的视图是检查Django基于类的视图的一个很棒的资源.以下是两个类的链接:
https://ccbv.co.uk/projects/Django/1.9/django.views.generic.edit/FormView/ https://ccbv.co.uk/projects/Django/1.9/django.views.generic.edit/ CreateView的/
检查我们form_valid
将看到最大差异的方法.
至于选择使用哪个,我认为这一切都取决于你的情况.如果你试图通过ModelForm
那时创建模型实例CreateView
可能对你更好,如果你正在做一些通用的东西,那么FormView
可能更适合.
class IndexView(TemplateView): template_name = 'main/index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update({ 'latest_posts': Post.objects.all().order_by('-created_at'), 'popular_posts': Post.objects.all().order_by('-views'), 'hot_posts': Post.objects.all().order_by('-score')[:25], 'categories': Category.objects.order_by('likes')[:5], }) return context class PostDetailView(DetailView): model = Post context_object_name = 'single_post' template_name = 'main/post.html' # note that these are already "slug" by default pk_url_kwarg = 'slug' slug_field = 'slug' def get_object(self, queryset=None): obj = seuper(PostView, self).get_object(queryset) obj.views += 1 obj.save() return obj class CategoryDetailView(DetailView): model = Category template_name = 'main/category.html' context_object_name = 'category' # note that these are already "slug" by default pk_url_kwarg = 'slug' slug_field = 'slug' def get_context_date(self, **kwargs): context = super(CategoryDetailView, self).get_context_data(**kwargs) context.update({ # really no need to put category_name in context # as you can simply do {{ category.name }} in your template # you can use relations to query related data 'posts': self.object.post_set.all() }) return context