Login

Snippets by hawkeye

Snippet List

UserForeignKey

Many models are tightly coupled to the default Django `User` model (`django.contrib.auth.models.User`). Sometimes this user model just doesn't fit everyone's needs. By using `UserForeignKey` it is possible to make the `User` model configurable, encouraging loose coupling. Additionally, this can help to prevent circular imports between `User` and another model. Use it like a standard `ForeignKey`... it accepts all the same arguments. If you want to use a `User` model other than the default, just add `USER_MODEL` to your settings file.... it uses dotted notation (`app_label.model_name`). Example: class BlogPost(models.Model): user = UserForeignKey(related_name="blog_posts") title = models.CharField(...) content = models.TextField(...)

  • foreignkey
  • user
  • auth
Read More

several_random template filter

Allows the selection of one or more items from a list. The built-int `random` filter only allows you to select a single at a time, and repeated use can return the same item many times. **Example:** `{% for random_item in item_list|several_random:3 %} ... {% endfor%}` **Note:** If you're running this on an uncached QuerySet, it can result in many database queries... a future improvement might check to see if the passed object is a QuerySet and act accordingly.

  • filter
Read More

HttpMethodsMiddleware

This middleware allows developers to "fake" browser support for HTTP methods. Even though most modern browsers only support GET and POST, the HTTP standard defines others. In the context of REST, PUT and DELETE are used for client interaction with the server. For forms with a PUT or DELETE method, this middleware will change them to go through POST, and will include an invisible field called "method_middleware_transform" that carries the originally intended method. So, `<form method="PUT" ...>...</form>` More or less becomes `<form method="POST" ...><input type=hidden name="method_middleware_transform" value="PUT"></form>` (with a few other minor HTML modifications) The process is completely transparent to the developer... you never have to deal with the fact that browsers don't support the standard methods. **One caveat** is that server interaction via `XMLHttpRequest` (AJAX) requires special attention... this middleware won't properly setup your XMLHttpRequest to take advantage of this functionality. This is a combination of the work of Jesse Lovelace and the Django CSRF middleware.

  • middleware
  • rest
Read More

hawkeye has posted 3 snippets.