When you have two models joined by a foreign key, it's common to want to retrieve a set of objects from the "target" of the foreign key based on whether there are any objects "pointing" to them. This snippet demonstrates how to do so, using the `extra` method of the default model manager.
Note that this is probably more efficient than using two ORM methods (e.g., selecting all values from one table, and using an `id__in` lookup on the other) since it does the whole thing in one query and avoids instantiating any intermediate objects.
Example (in project/application/models.py):
register_custom_permissions_simple((("is_editor", "User is editor"),))
In a view:
if not request.user.has_perm('application.is_editor'):
return HttpResonseRedirect(LoginUrl)
This code will add a thumbnail image to your Model's Admin list view. The code will also generate the thumb images, so the first view may be a little slow loading.
This assumes you have an **ImageField** in your Model called **image**, and the field's **upload_to** directory has a subdirectory called **tiny**. You then must add **"thumb"** to your Model's Admin **list_display**.
The thumbnail images are also linked to the full size view of the image.
I found this **VERY** useful... hope someone else does as well.
with this middleware you can use tidy to prettify your html, just add the class to the `MIDDLEWARE_CLASSES` setting.
tidy has an enormous number of options, se [Tidy Options Reference](http://tidy.sourceforge.net/docs/quickref.html) .
you must have [µTidylib](http://utidylib.berlios.de/) installed.
This is a [Django template tag](http://www.djangoproject.com/documentation/templates_python/#extending-the-template-system "Extending the template system") that renders an arbitrary block of text with Markdown and [Pygments](http://pygments.org "Syntax highlighter").
Use Markdown as usual, and when you have a code block to insert, put it inside `code` tags, with the language as the class:
`<code class='python'>print "Hello, World"</code>`
To use it in a template, first `{% load ... %}` the tag library, then `{{ content|render }}` your content.
The tag takes one optional argument, to enable safe rendering in markdown. To use it, call `{{ content|render:"safe" }}`.
Very simple filter that returns one of the following by default:
1. \# days ago
2. yesterday
3. today
4. January 01, 2007
Example template code:
This thread was started {{ post.date_created|dayssince }}.
This thread was started today.
E-mail sent: {{ email.date_sent|dayssince|capfirst }}
E-mail sent: Yesterday
Object created: {{ obj.date_created|dayssince|upper }}
Object created: 12 DAYS AGO
User's bogus birthday: {{ user.get_profile.bday|dayssince }}
User's bogus birthday: April 20, 3030
Django's transition from oldforms to newforms is nearing. If you're using recent trunk source code from Django's subversion repository, you should start using newforms.
But there are still some rough edges as of today. File uploading seems to be one of them. (Adrian and other Django folks are well aware of this. Please don't bother them by asking "Are we there yet?")
The Django mailing lists and Google searching didn't turn up any best practices for this area of newforms, so I muddled through it and here's the result. I omit the urls.py code necessary to hook up the zip_upload method to a URL, but otherwise this should be complete.
And if I haven't loaded this with enough caveats...please be aware this code may be obsoleted soon.
Authentication through Facebook's Graph API. See
[http://developers.facebook.com/docs/authentication/](http://developers.facebook.com/docs/authentication/)
[http://developers.facebook.com/docs/authentication/permissions](http://developers.facebook.com/docs/authentication/permissions)
[http://developers.facebook.com/docs/api](http://developers.facebook.com/docs/api)
[http://github.com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth.py](http://github.com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth.py)
Define the facebook tokens in settings.py and replace <app_name> with the name of your app. You will probably want to modify the scope on the authorize link in the template, see the authentication permissions link.
This updates the user model every time the user logs in but I think that it is okay so the data is always correct. I have tested this but not rigorously. If there is a hole and everyone gets admin rights to your site don't say I didn't warn you :).
Comments are appreciated.
16 June 2010 Added missing imports. Cleaned up the template.
Shouts out to @obeattie and @whalesalad
Here's a signal handler to log a user in on registration activation. It took me an hour to figure out that I needed to put the user.backend in quotes and google wasn't being my friend.
from [the django-registration documentation](http://docs.b-list.org/django-registration/0.8/faq.html):
How do I log a user in immediately after registration or activation?
You can most likely do this simply by writing a function which listens for the appropriate signal; your function should set the backend attribute of the user to the correct authentication backend, and then call django.contrib.auth.login() to log the user in.
You may notice that using Google Analytics's 'urchin' with the CacheMiddleware and SessionMiddleware or AuthenticationMiddleware middleware classes means that nothing is ever cached.
Google Analytics updates its cookies with every page view, and the Auth/Session middlewares add cookies to the caching engine's 'Vary' list. This means every page view is given a unique cache key.
This middleware class will remove urchin's '__utmX' cookies from the request object before it hits the caching middleware. Put it at the top of your MIDDLEWARE_CLASSES in settings.py.
nf / [email protected]
This template tag provides an easy way to render objects in your template, even if you don't know ahead of time what type they are.
For example, if you've got a search page with a result list comprised of objects from various models, you can simply loop through them and render them using the tag. The tag will choose the best template and render the object for you.
The tag's docstring has all the details. I hope you find this as useful as I have. Questions, comments, complaints welcome.
This view snippet is a helper for implementing file download handlers. There is a standard to encode Unicode filenames properly, but many browsers have different protocols.
The default encoding is assumed to be UTF-8.
A generic admin action to export selected objects as csv file. The csv file contains a first line with header information build from the models field names followed by the actual data rows.
Access is limited to staff users.
Requires django-1.1.
**Usage:**
Add the code to your project, e.g. a file called actions.py in the project root.
Register the action in your apps admin.py:
from myproject.actions import export_as_csv
class MyAdmin(admin.ModelAdmin):
actions = [export_as_csv]
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.