In this type of model you are allowed to define a model with a generic type.
For instance, a location can be an address, GPS coordinates, an intersection and many others types. Using a many to many field, models can have multiple locations without worrying about the type of location referencing. New locations types can be added without changing the references in other models.
This code is also used in Django's built in ContentTypes app.
This class simplies the Feed class of django. The differences are:
1. Don't need define title and description template file
2. default feed generator class is Atom1Feed
3. According feed_url, EasyFeed can auto get the domain field, and you can also specify the domain parameter.(feed_url should be a full domain path, so you can use [Get the full request path](http://www.djangosnippets.org/snippets/41/) to get the full path of the feed url.)
4. There is a helper function render_feed() to return a response value.
example
---------
Feed class:
class BookCommentsFeed(EasyFeed):
def __init__(self, feed_url, book_id):
super(BookCommentsFeed, self).__init__(feed_url)
self.book_id = book_id
self.book = Book.objects.get(id=int(book_id))
def link(self):
return '/book/%s' % self.book_id
def items(self):
return self.book.comment_set.all().order_by('-createtime')[:15]
def title(self):
return 'Comments of: ' + self.book.title
def description(self):
return self.book.description
def item_link(self, item):
return '/book/%s/%s' % (self.book_id, item.chapter.num)
def item_description(self, item):
return item.content
def item_title(self, item):
return '#%d Comment for: ' % item.id + item.chapter.title
def item_pubdate(self, item):
return item.createtime
def item_author_name(self, item):
return item.username
And the view code is:
from feeds import *
from utils.easyfeed import render_feed
from utils.common import get_full_path
def bookcomments(request, book_id):
return render_feed(BookCommentsFeed(get_full_path(request), book_id))
Enables cookie based authentication with apache.
I needed user authentication for some static files, but couldn't use the method described [here](http://www.djangoproject.com/documentation/apache_auth/) as this prompts the user for his credentials, making him log in twice. There is some overhead in the code, because it runs all request middleware components (only session and auth would be needed). All arguments described in the link above are supported.
I use it like this in the apache config:
<Location "/protected/location">
PythonPath "['/path/to/proj/'] + sys.path"
PythonOption DJANGO_SETTINGS_MODULE myproj.settings
PythonOption DjangoPermissionName '<permission.codename>'
PythonAccessHandler my_proj.modpython #this should point to accesshandler
SetHandler None
</Location>
This middleware will add a log of the SQL queries executed at the bottom of every page. You can (should) use BeautifulSoup to place this in a specific location.
Note: If you serve non-html content, it would be wise to do a mimetype check.
This will perform a regular expression search/replace on a string in your template.
`{% load replace %}`
`{{ mystring|replace:"/l(u+)pin/m\1gen" }}`
If:
`mystring = 'lupin, luuuuuupin, and luuuuuuuuuuuuupin are lè pwn'` then it will return:
`mugen, muuuuuugen, and muuuuuuuuuuuuugen are lè pwn`
The argument is in the following format:
[delim char]regexp search[delim char]regexp replace
Allows you to override form fields created by form_for_model or form_for_instance, without having to redefine whole fields for example in form.base_fields.
Use this code to generate downloadable [vCard][] objects. See the [VObject docs][1] for more details on the API.
[1]: http://vobject.skyhouseconsulting.com/
[vcard]: http://en.wikipedia.org/wiki/VCard
[Snippet #2](http://www.djangosnippets.org/snippets/2/) demonstrated some cool tricks possible with manager methods. This example shows how to assign and use a custom manager method.
In this snippet the `belongs_to_user` method returns an Account queryset containing only those accounts associated with the specified user. The method is useful because it hides the implementation of User in the Account model.
Line 17 associates the custom manager with the Account model.
A patch (against django svn trunk [4649](http://code.djangoproject.com/browser/django/trunk/?rev=4649)) that allows users to log in with Basic HTTP Authentication i.s.o. login forms using some simple middleware (entire patch is ~50 lines). I was unaware of http://code.djangoproject.com/wiki/GenericAuthorization so I'm not sure about its usefulness in the long run.
You can enable it by including 'django.contrib.auth.middleware.BasicAuthenticationMiddleware' in your MIDDLEWARE_CLASSES and then adding the following lines in your settings.py:
BASIC_WWW_AUTHENTICATION = True
WWW_AUTHENTICATION_REALM = "djangolures.com"
Updated: See also http://code.djangoproject.com/ticket/3609 (patch now availble here as well).
Using newforms you can create forms from existing models easily and automatically with either `form_for_model(class)` or `form_for_instance(instance)`. Usually the automagically generated form fields are sufficient; however, sometimes you need to restrict selections in a choice field.
You can also set the default selection when instantiating the form. In this example, if `acct` is not contained in the 'account' field choices, the selection defaults to the first entry.
This example is probably not good practice when using `form_for_instance` because the existing value 'selection' of the choice field is lost and must be reset manually (see above).
I use this script to keep track of the cache usage for various sites. It presently only supports memcached because that's all that I use, but leave a comment with patches for other systems and I'll add them.
This is a really useful function I used to create the resized preview images you can see on the [homepage of my site](http://www.obeattie.com/). Basically, it takes the original URL of an image on the internet, creates a resized version of that image by fitting it into the constraints specified (doesn't distort the image), and saves it to the MEDIA_ROOT with the filename you specify.
For example, I use this by passing it the URL of a Flickr Image and letting it resize it to the required size, and then saving it to a local path. It then returns the local path to the image, should you need it. I however just construct a relative URL from the image_name and save that to the database. This way, it's easy to display this image.
Hope it's useful!
Returns a sharpened copy of an image.
Resizing down or thumbnailing your images with PIL.Image tends to make them blurry. I apply this snippet to such images in order to regain some sharpness.
A way to implement models with translatable content.
The translatable field of the default language has no extension, like "title" and the translations have extensions postfixes "_<two-letter language code>", like "title_la" or "title_mn". Method get_title() in this case returns the translation of the currently chosen language or the title of the default language, if the translation is not set.
The class XFieldList overrides the default list class and is used for modifying ordering and list_display settings according the chosen language. For example, when the German language is chosen, the list of translatable content objects will be ordered by German titles (not English).
*At the time when the list of field names is assigned to ordering or list_display (at the import of the model), the currently chosen language is still not known. But the language is known when ordering and list_display lists are used in contributed administration or elsewhere.*
The XFieldList returns the modified values of the passed-in list, when its methods/properties are triggered. XFieldList transforms field names ending "_" (except the ones beginning with "__", like "__str__") to appropriate translations according the currently chosen language. For example ['title_', 'content_', 'is_published'] will be changed to ['title', 'content', 'is_published'] for the English language and to ['title_lt', 'content_lt', 'is_published'] for the Lithuanian language.
*The best practice is to put XFieldList into a separate file and import it from different apps whenever needed.*
It's worth mentioning that one implementing this should also know about [Django internationalization](http://www.djangoproject.com/documentation/i18n/).
`foo = dynamic_import ( 'rawr.i.am.a.lion' )`
Will import `lion` from `rawr.i.am.a` and return it. (This isn't really Django specific)
Props to Crast for the original.