**This is a model field for managing user-specified positions.**
Usage
=====
Add a `PositionField` to your model; that's just about it.
If you want to work with all instances of the model as a single collection, there's nothing else required. In order to create collections based on another field in the model (a `ForeignKey`, for example), set `unique_for_field` to the name of the field.
It's probably also a good idea to wrap the `save` method of your model in a transaction since it will trigger another query to reorder the other members of the collection.
Here's a simple example:
from django.db import models, transaction
from positions.fields import PositionField
class List(models.Model):
name = models.CharField(max_length=50)
class Item(models.Model):
list = models.ForeignKey(List, db_index=True)
name = models.CharField(max_length=50)
position = PositionField(unique_for_field='list')
# not required, but probably a good idea
save = transaction.commit_on_success(models.Model.save)
Indices
-------
In general, the value assigned to a `PositionField` will be handled like a list index, to include negative values. Setting the position to `-2` will cause the item to be moved to the second position from the end of the collection -- unless, of course, the collection has fewer than two elements.
Behavior varies from standard list indices when values greater than or less than the maximum or minimum positions are used. In those cases, the value is handled as being the same as the maximum or minimum position, respectively. `None` is also a special case that will cause an item to be moved to the last position in its collection.
Limitations
===========
* Unique constraints can't be applied to `PositionField` because they break the ability to update other items in a collection all at once. This one was a bit painful, because setting the constraint is probably the right thing to do from a database consistency perspective, but the overhead in additional queries was too much to bear.
* After a position has been updated, other members of the collection are updated using a single SQL `UPDATE` statement, this means the `save` method of the other instances won't be called.
More
===
More information, including an example app and tests, is available on [Google Code](http://code.google.com/p/django-positions/).
This decorator allows edit or delete for the owner of the record. Snippet applies for every model that has ForeignKey to User. Works for User model too. Works with other decorators as permission_required or similar.
Decorator raise http 403 view if user is not owner.
**Usage**
@permission_required('blogs.change_entry')
@owner_required(Entry)
def manage_entry(request, object_id=None, object=None):
Decorator populates object kwargs if object_id present, otherwise just returns original view function.
@permission_required('blogs.delete_entry')
@owner_required()
def entry_delete(*args, **kwargs):
kwargs["post_delete_redirect"] = reverse('manage_blogs')
return delete_object(*args, **kwargs)
In generic delete wrapper view returns original view function.
There is a sample in the code.
You can use this snippet to allow your forms to easily edit object locations.
Take care about what you should add to your templates in order to make it work.
This server-side middleware implements some of the functionality in the Yahoo
User Interface Loader component. YUI JavaScript and CSS modules requirements
can be declared anywhere in the base, inherited or included templates, and the
resulting, optimized `<script>` and `<link rel="stylesheet">` tags are inserted at
the specified position of the resulting page.
Requirements may be specified in multiple locations. This is useful when zero
or more components are included in the HTML head section, and inherited and/or
included templates require possibly overlapping sets of YUI components in the
body across inherited and included templates. All tags are collected in the
head section, and duplicate tags are automatically eliminated.
The middleware understands component dependencies and ensures that resources
are loaded in the right order. It knows about built-in rollup files that ship
with YUI. By automatically using rolled-up files, the number of HTTP requests
is reduced.
The default syntax looks like HTML comments. Markup for the insertion point is
replaced with `<script>` and `<link>` tags:
<!-- YUI_init -->
Component requirements are indicated, possibly in multiple locations, with the
`YUI_include` markup. It is removed from the resulting page by the
middleware. Example:
<!-- YUI_include fonts grids event dragdrop -->
Non-minified and compressed versions are requested, respectively, by:
<!-- YUI_version raw -->
<!-- YUI_version debug -->
Example:
<html><head>
<!-- YUI_init -->
<!-- YUI_include dom event -->
</head><body>
<!-- YUI_include element selector reset fonts base -->
</body></html>
Renders:
<html><head>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/reset-fonts/reset-fonts.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/base/base-min.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/element/element-beta-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/selector/selector-beta-min.js"></script>
</head><body>
</body></html>
The markup format can be customized with global Django settings. Example:
YUI_INCLUDE_PREFIX_RE = r'{!'
YUI_INCLUDE_SUFFIX_RE = r'!}'
would change markup to e.g. `{! init !}` and `{! include dom event !}`.
The base URL is customized with the `YUI_INCLUDE_BASE` setting, e.g.:
YUI_INCLUDE_BASE = 'http://localhost:8000/yui/build/'
To remove the XHTML trailing slash from the `<link>` tag, use:
YUI_INCLUDE_CSS_TAG = '<link rel="stylesheet" type="text/css" href="%s">'
See also the [home page for this module](http://trac.ambitone.com/ambidjangolib/wiki/YUI_include).
As a demo, I was asked to write a `render_to_file()` function to load a template and render it to a file. Turns out it's amazingly easy, and I think it's a neat trick to have in your bag of tools.
Example model:
class MyModel(models.Model):
file = RemovableFileField(upload_to='files', \
null=True, blank=True)
image = RemovableImageField(upload_to='images', \
null=True, blank=True)
A delete checkbox will be automatically rendered when using ModelForm or editing it using form_for_instance. Also, the filename or the image will be displayed below the form field. You can edit the render method of the DeleteCheckboxWidget or add one to RemovableFileFormWidget to customize the rendering.
UPDATE: 5. April 2009. Making it work with latest Django (thanks for the comments).
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(...)
Requires the twitter module (easy_install python_twitter).
Your project settings file should define TWITTER_USERNAME.
Call the tag like:
`
{% get_twitter_status as tweet tweet_time tweet_url %}
<p><q cite="{{ tweet_url }}">{{ tweet }}</q> ({{ tweet_time }})</p>
`
**EDIT**: I've also included an alternative method as suggested in the comments. Called with:
`
{% get_twitter_status as tweet %}
<p><q cite="{{ tweet.url }}">{{ tweet.status }}</q> ({{ tweet.time }})</p>
`
This is my personal tagging system that I have created. It is intended to be used for multiple applications. This tagging system also has a build in tag cloud that will generate based on the most frequently used tags that you have used or based on the number of clicks users have clicked on a particular tag.
If you need to upload Image files into folders qualified with user name eg.: 'images/user1/2008/01/01' then you may use this snippet.
In order to use it you have to install ThreadLocals middleware as described here:
http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser
Then just import UserImageField class at your models.py and specify 'upload_to' parameter with '%(user)s' in the path eg.:
`
image3 = UserImageField(_('Image 3'),
upload_to='flower_images/%(user)s/%Y/%m/%d',
null=True,
blank=True)
`
Custom template filter to generate a breadcrumb trail for a flatpage. Say you have a series of flatpages with URLs like /trunk/branch/leaf/ etc. This filter looks at the URL of a given flatpage, figures out which of the leftwards text chunks correspond to other flatpages, and generates a string of anchored HTML.
Usage:
{% load make_breadcrumb_trail %}
{{ flatpage.url|crumbs:flatpage.title }}
I use this to integrate a google map in a form renderd by newforms. If someone click on the map and set a icon, the Latitude and Longitude data goes into the 2 form fields.
You need to generate a google API key (http://www.google.com/apis/maps/signup.html) for the GOOGLE_KEY variable.
Adds a shortcut to edit releated objects right/ForeignKey fields.
an edit symbol will be shown right next to the "add annother" link on all select boxes,
with opens the releated object currently selected in a popup window.
**depends on jquery**
Add this to the head of "templates/admin/base.html".
you may need to add
`<script type="text/javascript" src="/path/to/jquery.js"></script>`
before it
You can switch boolean fields in the admin without editing objects
Usage:
`
class News(models.Model):
# ...
pub = models.BooleanField(_('publication'),default=True)
# ...
pub_switch = boolean_switch(pub)
class Admin:
list_display = ('id', 'pub_switch')
`
Thanks for [svetlyak](http://www.djangosnippets.org/snippets/398/).
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.