Using Django REST Framework for Model views there is always the issue of making duplicated queries without either prefetching the objects that will be accessed using the serializer and as such will lead to large number of queries being made to the database.
This will help in optimizing the queryset used for the viewset by accessing the `_meta.fields` property of the serializer.
Use this class to partially update one or more fields of a model. Only the fields that are bound to the form via the "data" parameter in the constructor get updated. All automatically generated fields have their "required" attribute set to False.
Example 1:
from django.contrib.auth.models import User
class PatchUserForm(PatchModelForm):
class Meta:
model = User
user = User.objects.get(username='old_username')
form = PatchUserForm(data={'username':'new_username'}, instance=user)
form.is_valid()
form.save()
Example 2:
from django.contrib.auth.models import User
class PatchUserForm(PatchModelForm):
class Meta:
model = User
user = User.objects.get(pk=35)
form = PatchUserForm(data={'last_name':'Smith', 'is_staff': True}, instance=user)
form.is_valid()
form.save()
Calls a view by request.method value.
To use this dispatcher write your urls.py like this:
urlpatterns = pattern('',
url(r'^foo/$', dispatch(head=callable1,
get=callable2,
delete=callable3)),
)
If `request.method` is equal to head, `callable1` will be called as your usual view function;
if it is `get`, `callable2` will be called; et cetera.
If the method specified in request.method is not one handled by `dispatch(..)`,
`HttpResponseNotAllowed` is returned.
This might be a bit cludgy. But the idea is to extend model definition with mixins that can help with defining standard views. So defining a new model as inheriting from Model and All, would allow automatic definition of /get /post type accessors.
Yet another implementation of class based RESTful dispatch. This particular implementation features:
* You do not have to call __init__ from the derived classes.
* Avoids __metaclass__ which (in our environment) led to unexpected method override behavior.
* Method names match the google webapp API.
* One new instance per request to reduce errors in multi-threaded code.
Snippets of inspiration:
* [436](http://www.djangosnippets.org/snippets/436/)
* [437](http://www.djangosnippets.org/snippets/437/)
* [1071](http://www.djangosnippets.org/snippets/1071/)
* [1072](http://www.djangosnippets.org/snippets/1072/)
* [1226](http://www.djangosnippets.org/snippets/1226/)
This is a field that allows multiple markup types but also stores the pre-rendered result in the database which offers an advantage over calling one of the render methods each time. Example usage looks like:
class BlogPost(models.Model):
...
post = MarkupField()
the various extra fields can then be accessed as follows:
BlogPost.objects.get(pk=1).post # raw content
BlogPost.objects.get(pk=1).post_markup_type # markup type (plain text, html, markdown, rest, textile)
BlogPost.objects.get(pk=1).post_rendered # content of post rendered to html
BlogPost.objects.get(pk=1).post_as_html # property that access post_rendered but marked safe for easy use in templates
After writing my initial version of this I was pointed at the similar http://www.djangosnippets.org/snippets/1169/
I find mine a bit more useful as it includes ReST and includes a mark_safe call to allow showing the rendered HTML directly. I have however borrowed the nice idea of dynamically building MARKUP_TYPES from #1169.
Also available via http://gist.github.com/67724.
Inspired by [Eric Florenzano's](http://www.eflorenzano.com/) post about [writing simple and very fast pure-WSGI applications](http://www.eflorenzano.com/blog/post/writing-blazing-fast-infinitely-scalable-pure-wsgi/). Using [RestView](http://www.djangosnippets.org/snippets/1071/) approach. More about it on [my blog](http://my.opera.com/kubiku/blog/2009/01/16/bare-wsgi-vs-python-frameworks-django-chapter)
Subclass `Resource` to create a view that will dispatch based on the HTTP method of the request.
class View(Request):
def DELETE(self, request):
...
def GET(self, request):
...
def PUT(self, request):
...
Other snippets provided inspiration:
* [436](http://www.djangosnippets.org/snippets/436/)
* [437](http://www.djangosnippets.org/snippets/437/)
* [1071](http://www.djangosnippets.org/snippets/1071/)
* [1072](http://www.djangosnippets.org/snippets/1072/)
The code is also available on [GitHub](http://github.com/jpwatts/django-restviews/).
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.
Sometimes it's useful to dispatch to a different view method based on request.method - e.g. when building RESTful APIs where GET, PUT and DELETE all use different code paths. RestView is an extremely simple class-based generic view which (although it's a stretch to even call it that) which provides a simple mechanism for dividing up view logic based on the HTTP method.
This decorator handle a extra "action" parameter from an url and call this desired action in the provided views module.
Example:
from posts import views
urlpatterns = patterns('posts.views',
...
url(r'^(?P<id>\d+)/(?P<action>delete|publish|edit)/$', action(views), name="posts-action"),
...
)
In templates:
{% url posts-action id=post.id,action="delete" %}
**Attention! This snippet must be ignored**, like [zgoda](http://www.djangosnippets.org/users/zgoda/) pointed with reason: already exists this functionality in `markup` contrib.
**Explanations:**
This template filter allows you to render easily a reStructuredText to **HTML** or another format it supports.
**Setup:**
Insert the snippet into an_app/templatetags/restutils.py.
**Use in template:**
`{% load restutils %}` and use it as following:
- `{{ entry.content|rest:"html" }}`
In the same vein as [snippet 436](http://www.djangosnippets.org/snippets/436/), this allows you to differentiate view logic by HTTP method such as GET, POST, PUT, DELETE.
This is also very useful combined with the [HttpMethodsMiddleware snippet](http://www.djangosnippets.org/snippets/174/).
I am not the author, but I have found it to be very helpful.