Django does not have a clean, built-in mechanism to separate GET and POST implementations. This simple decorator provides this behavior. Django does provide an alternate way using class-based views, but defining class for each of your view functions may be an overkill. You can name the get and post functions anything you wish, but you need to make sure they are returned in the same order (get first and then post).
Example usage:
@formview
def edit(request, id):
form = EditForm(id, request.POST or None)
def get():
return render(request, 'edit.html', {'form' : form})
def post():
if form.is_valid():
form.save(id)
return redirect('list')
return get, post
I have a model with a datetime field that I used as a timestamp. I’m in California’s timezone (“America/Los_Angeles”). The data is saved in UTC in MySQL (as confirmed by the ORM). I just want to do a query that looks like this: “give me all the information with day X’s timestamp” (24 hour period). But the timestamp is a datetime, not date. If you just do varname.date(), it’s still UTC’s date, not your local timezone’s date.
Here’s what I did:
1. First construct the start and end time period covering the 24 hour period of that day you want
2. Make it an “aware” (not naive) datetime
3. Filter for the __range
Intro
-----
I found a question on SO for which Justin Lilly's answer was correct but not as thorough as I'd like, so I ended up working on a simple snippet that shows how to bind signals at runtime, which is nifty when you want to bind signals to an abstract class.
Bonus: simple cache invalidation!
Question
--------
[How do I use Django signals with an abstract model?](http://stackoverflow.com/questions/2692551/how-do-i-use-django-signals-with-an-abstract-model)
I have an abstract model that keeps an on-disk cache. When I delete the model, I need it to delete the cache. I want this to happen for every derived model as well.
If I connect the signal specifying the abstract model, this does not propagate to the derived models:
pre_delete.connect(clear_cache, sender=MyAbstractModel, weak=False)
If I try to connect the signal in an init, where I can get the derived class name, it works, but I'm afraid it will attempt to clear the cache as many times as I've initialized a derived model, not just once.
Where should I connect the signal?
Answer
------
I've created a custom manager that binds a post_save signal to every child of a class, be it abstract or not.
This is a one-off, poorly tested code, so beware! It works so far, though.
In this example, we allow an abstract model to define CachedModelManager as a manager, which then extends basic caching functionality to the model and its children. It allows you to define a list of volatile keys that should be deleted upon every save (hence the post_save signal) and adds a couple of helper functions to generate cache keys, as well as retrieving, setting and deleting keys.
This of course assumes you have a cache backend setup and working properly.
An HttpResponse for giving the user a file download, taking advantage of X-Sendfile if it's available, using FileWrapper if not.
Usage:
HttpResponseSendfile('/path/to/file.ext')
To bypass the fallback:
HttpResponseSendfile('/path/to/file.ext', fallback=False)
This has been tested working with Lighttpd 1.4.28's mod_fastcgi.
This is a decorator which will gets Django to try the cache before computing the result of a function. It automatically builds the cache key as a hash of the function name and inputs, and allows you to set whatever timeout you want.
Based on [#2020](http://djangosnippets.org/snippets/2020/)
This snippet creates a simple generic export to csv action that you can specify the fields you want exported and the labels used in the header row for each field. It expands on #2020 by using list comprehensions instead of sets so that you also control the order of the fields as well.
Function and usage in views and template with django-paypal to have encrypted paypal buttons with a cart(adding multiple elements).
All credits go to Jon Atkinson, http://jonatkinson.co.uk/paypal-encrypted-buttons-django/
I just added it here with a complete implementation using a cart(his example didnt include it).
I know there is some redundancy in the data passed to the dict and the submit form, i'm just not sure what can i take out, the paypal docs are not clear about it, if you test this code without some of the data and it works, please tell me.
The key parts are the cmd _s-xclick and again the cmd '_cart' both are needed.
Based on [#1879](http://djangosnippets.org/snippets/1879/) and [#2356](http://djangosnippets.org/snippets/2356/)
Works in Django 1.3
Hopefully it's generic enough to implement a compact (sparse) version of whatever custom filter you need.
Small function that i use to save files to an imagefield, the file can be either an url or a file.
This function has the following requirements.
import requests
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
from django.conf import settings
Get the awesome requests library: pip install requests
This function uses MEDIA_ROOT to know the location of the static dir, you can change that chaging the static_dir variable.
On our site [Fornebuklinikken - A cosmetic surgeon in Norway](http://www.fornebuklinikken.no) we also have a domain [http://fornebuklinikken.com](http://www.fornebuklinikken.no) which should be using the 'en' language.
We didn't wan't to use the standard locale lib, and wrote our own middleware which lookups the correct language corresponding to the domain (.no or .com)
Any questions? Contact me on herman.schistad (at) gmail.com
These snippets together give you the ability to view all Django SQL queries executed across all incoming requests by visiting a particular URL (`/profiling` in the example). This is useful when developing with the Django test server.
This is useful if most of the incoming requests are AJAX requests, because in such cases the debug toolbar will not be able to show which queries got executed.
The `SqlProfilingMiddleware` class is the key one. At the end of every incoming request it appends the executed SQL queries to a static class member list. Any information request profiling information can be added in this way.
The snippet does not add any security around viewing such information. This was done just to keep the code simple. But when implementing this you will definitely want to restrict access to this URL to only people allowed to view such information.
I needed a way to find if a menu items should be active. After searching the internet i found a few options*, but none of them did fit my needs, so i wrote my own:
Usage:
<a href="{% url 'view-name' %}" class="{% current request 'view-name' %}"></a>
* http://gnuvince.wordpress.com/2008/03/19/the-new-and-improved-active-tag/
* http://stackoverflow.com/questions/340888/navigation-in-django
This templatetag was inspired by: [Admin App/Model Custom Ordering](http://djangosnippets.org/snippets/1939/).
I rewrote it from scratch because it wasn't working on my install.
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.