转换为基于类的视图,如何以及为什么?

时间:2015-12-06 12:24:40

标签: django

似乎大多数人使用基于类的视图而不仅仅是无聊的功能。我通过免费的在线教程学习了django,他们并没有真正告诉我基于类的视图(至少我做过的)。 如果有人能告诉我如何将我的功能转变为基于类的视图,我将非常感激。为什么他们优于功能。我对函数很满意,但遗憾的是我想要理解的大多数例子都是基于类的视图。这是我的代码。

def index(request):

    categories = Category.objects.order_by('likes')[:5]
    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]

    context_dict = {
        'latest_posts': latest_posts,
        'popular_posts': popular_posts,
        'hot_posts': hot_posts,
        'categories': categories
    }
    return render(request, 'main/index.html', context_dict)
#for single-post page
#we use uuslug 
def post(request, slug):
    single_post = get_object_or_404(Post, slug=slug)
    single_post.views += 1  # increment the number of views
    single_post.save()      # and save it
    context_dict = {
      'single_post' :single_post,
    }

    return render(request, 'main/post.html', context_dict)
#for category page
#we use slugfield this time 
def category(request, category_name_slug):
  context_dict = {}
  try:
    category = Category.objects.get(slug=category_name_slug)
    context_dict['category_name'] = category.name

    posts = Post.objects.filter(category=category)
    context_dict['posts'] = posts
    context_dict['category'] = category
  except Category.DoesNotExist:
    pass

  return render(request, 'main/category.html', context_dict)
#for adding category

def add_category(request):
  if request.method == 'POST':
    form = CategoryForm(request.POST)
    if form.is_valid():
      form.save(commit=True)
      return index(request)
    else:
      print form.errors
  else:
    form = CategoryForm()

  return render(request, 'main/add_category.html', {'form':form})

我尝试添加add_category

class categoryCreateView(CreateView):

   model = Category
   form_class = CategoryForm
   template_name = 'main/add_category.html'

   def form_valid(self, form):
      self.object = form.save(commit=False)
      # any manual settings go here
      self.object.save()
      return HttpResponseRedirect(reverse('category', args=[self.object.slug]))

   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
      return super(categoryCreateView, self).dispatch(request, *args, **kwargs)

EDIT ::

class CategoryFormView(FormView):
    form_class = CategoryForm
    template_name = 'main/add_category.html'

    def get_success_url(self):
        return self.request.build_absolute_uri(reverse('category', args=[self.object.slug]))

    def get_context_data(self, **kwargs):
        context = super(CategoryFormView, self).get_context_data(**kwargs)
        # Add any extra context data needed for form here.
        return context

@method_decorator(login_required)
       def dispatch(self, request, *args, **kwargs):
          return super(categoryCreateView, self).dispatch(request, *args, **kwargs)

urls.py

来自django.conf.urls导入网址 从主要导入视图 来自django.core.urlresolvers导入反向 来自views import *

urlpatterns = [
    url(r'^$', views.index, name='index'),

    #url(r'^add_post/', views.add_post, name='add_post'),
    url(r'^add_post/$', login_required(CategoryFormView.as_view(), name='post-add'),

    url(r'^(?P<slug>[\w|\-]+)/edit/$', PostUpdateView.as_view(), name='post-edit'),
    url(r'^(?P<slug>[\w|\-]+)/delete/$', PostDeleteView.as_view(), name='post-delete'),


    url(r'^add_category/', CategoryFormView.as_view, name='add_category'),
    url(r'^(?P<slug>[\w|\-]+)/$', views.post, name='post'),

    url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),
    ]

1 个答案:

答案 0 :(得分:0)

而不是CreateView,只需创建一个FormView

class CategoryFormView(FormView):
    form_class = CategoryForm
    template_name = 'main/add_category.html'

    def get_success_url(self):
        return self.request.build_absolute_uri(reverse('category', args=[self.object.slug]))

    def get_context_data(self, **kwargs):
        context = super(CategoryFormView, self).get_context_data(**kwargs)
        # Add any extra context data needed for form here.
        return context