Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Class-Based Views

Kenneth Love
September 26, 2011

Class-Based Views

A short introduction to class-based views in Django 1.3. From the lightning talks at DjangoCon 2011

Kenneth Love

September 26, 2011
Tweet

More Decks by Kenneth Love

Other Decks in Programming

Transcript

  1. The Dumb & Lazy Guide to Class-based Views Kenneth Love

    (with apologies/thanks to Daniel Greenfeld)
  2. Old

  3. @login_required def awesome_view(request): if request.method == “POST”: form = AwesomeForm(request.POST)

    if form.is_valid(): form.save() return HttpResponseRedirect(reverse(‘awesome’)) else: form = AwesomeForm() return render(“awesome.html”, {‘form’: form}) @login_required def awesome_view(request): form = AwesomeForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(‘awesome’) return render(“awesome.html”, {‘form’: form})
  4. New

  5. Class MyAwesomeView(TemplateView): template_name = “awesome.html” def get(self, request): form =

    AwesomeForm() return self.render_to_response({‘form’: form}) def post(self, request): form = AwesomeForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(‘awesome’)) return self.render_to_response({‘form’: form})
  6. Class MyAwesomeView(TemplateView): template_name = “awesome.html” def get(self, request): form =

    AwesomeForm() return self.render_to_response({‘form’: form}) def post(self, request): form = AwesomeForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(‘awesome’)) return self.render_to_response({‘form’: form})
  7. Class MyAwesomeView(TemplateView): template_name = “awesome.html” def get(self, request): form =

    AwesomeForm() return self.render_to_response({‘form’: form}) def post(self, request): form = AwesomeForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(‘awesome’)) return self.render_to_response({‘form’: form})
  8. Class MyAwesomeView(TemplateView): template_name = “awesome.html” def get(self, request): form =

    AwesomeForm() return self.render_to_response({‘form’: form}) def post(self, request): form = AwesomeForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(‘awesome’)) return self.render_to_response({‘form’: form})
  9. Class MyAwesomeView(TemplateView): template_name = “awesome.html” @method_decorator(login_required) def dispatch(self, *args, **kwargs):

    return super(MyAwesomeView, self).dispatch(*args, **kwargs) def get(self, request): form = AwesomeForm() return self.render_to_response({‘form’: form}) def post(self, request): form = AwesomeForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(‘awesome’)) return self.render_to_response({‘form’: form})