Login

Tag "view-as-a-class"

Snippet List

FormHandler - take the legwork out of form processing

Take the legwork out of processing forms. Most people have a very specific structure to how they process forms in views. If the request method is "GET", then some HTML (with the blank form) is rendered. If the method is "POST", then the form is validated. If the form is invalid, some other HTML is displayed. If valid, the data is submitted and processed in some way. In order to do this all in a much nicer way, simply subclass `FormHandler`, define three methods (`valid`, `invalid` and `unbound`), point to the form, and use the subclass as your view in the URLconf.

  • views
  • forms
  • view
  • form
  • view-as-a-class
  • formhandler
  • form-handler
Read More

Resource

The `Resource` class is a way of writing a Django view as a class. I've done this as part of an effort to write easier-to-understand RESTful apps, as this allows the grouping of similar views as different types of operation on a resource. Essentially, the solution goes something like this: * Views have to be callables which return HttpResponse objects. * The problem with views as classes is that calling a view class returns an instance of the view class, not HttpResponse. * Solution: have the VC (view class) a subclass of HttpResponse. This way, 'calling' the class will return a HttpResponse instance. The `Resource` class performs a dispatch on the request method, so that a resource can be retrieved, created/updated and deleted by writing 'get', 'put' and 'delete' methods on a subclass of `Resource`. A general `Book` class shows how this might work for the case of 'books' in a system: class Book(Resource): def get(self, request, book_name): book = myapp.models.Book.objects.get(name=book_name) return render_to_response('book_template.html', {'book': book}) def put(self, request, book_name): new_book, created = get_or_create(myapp.models.Book, name=book_name) new_book.data = request.raw_post_data if created: return HttpResponse(status=201) return HttpResponse(status=200) def delete(self, request, book_name): book = myapp.models.Book.objects.get(name=book_name) book.delete() return HttpResponse() As you can see, classes can return responses, and these will be merged back into the returned response by the `Resource._update` method.

  • rest
  • resource
  • view-class
  • view-as-a-class
Read More

2 snippets posted so far.