Here is a way to get a drop down list from a queryset, with a list of "featured" items appearing at the top (from another queryset). This can be used for long select boxes which have a subset of commonly used values. The empty label is used as a separator and values can appear in both the featured set and the full set (it's more usable if they are in both).
For example a country drop down list with 5 featured countries might look like this:
Andorra
Australia
Kazakhstan
Singapore
Turkey
------------
Afghanistan
Albania
Algeria
American Samoa
Andorra
Angola
(hundreds more)
To use this, define your form field like this:
country = FeaturedModelChoiceField(queryset=Country.objects.all(),
featured_queryset=Country.objects.featured())
Simple middleware+decorator to handle age verification. Modeled after `django.contrib.sessions.middleware` to add an attribute to `request.user` called `is_age_verified` with consideration to [snippet 1002](http://www.djangosnippets.org/snippets/1002/). Decorator modeled after `django.contrib.auth.decorators.login_required`
Installation:
Create `verify_age` URLconf in `urls.py`
Create age verification page that URLconf points to
Define `settings.VERIFY_AGE_URL` based on URLconf
Add `age_verification.AgeVerificationMiddleware` to `MIDDLEWARE_CLASSES`
Import both `age_verification_required` and `REDIRECT_FIELD_NAME` in `views.py`
Implement `age_verification.AgeVerification.verify` somewhere to set session attribute on successful verification.
Use `@age_verification_required` decorator for views requiring age verification
Example urls.py:
urlpatterns += patterns('mahalo.answers.views',
...
url(r'^verify_age/?$', 'verify_age', name="verify_age"),
...
Example settings.py:
...
VERIFY_URL = '/verify_age/'
...
MIDDLEWARE_CLASSES += (
...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'myproject.contrib.middleware.age_verification.AgeVerificationMiddleware',
...
Example views.py:
from myproject.contrib.decorators import age_verification_required, REDIRECT_FIELD_NAME
from myproject.contrib.middleware.age_verification import AgeVerification
...
@age_verification_required
def some_view(request):
return render_to_response("index.html", {})
def verify_age(request):
# project specific
template_vars = default_template(request)
# form was posted
if request.POST.has_key("month") and request.POST.has_key("day") and \
request.POST.has_key("year"):
# "verify" user
av = AgeVerification(request.session)
av.verify()
if request.POST.has_key(REDIRECT_FIELD_NAME):
return HttpResponseRedirect(request.POST[REDIRECT_FIELD_NAME])
else:
return HttpResponseRedirect(reverse("root"))
# no form posted, show it
else:
if request.GET.has_key(REDIRECT_FIELD_NAME):
template_vars["next"] = request.GET[REDIRECT_FIELD_NAME]
return render_to_response("verify_age.html", template_vars)
These examples assume `age_verification.py` lives in `myproject/contrib/middleware/` and `decorators.py` lives in `myproject/contrib/`
If you have a relatively small finite number of categories (e.g. < 64), don't want to add a separate column for each one, and don't want to add an entire separate table and deal with joins, this field offers a simple solution.
You initialize the field with a list of categories. The categories can be any Python object. When saving a set of categories, the field converts the set to a binary number based on the indices of the categories list you passed in. So if you pass in as your categories list [A,B,C,D] and set model.categories = [C,D], the integer stored in the database is 0b1100 (note that although the categories list has a left-to-right index, the binary number grows right-to-left).
This means that if you change the order of your category list once you have data in the DB, you'll need to migrate the data over to the new format. Adding items to the list should be fine however.
If you need to do filtering based on this field, you can use bitwise operators. Django currently (to my knowledge) doesn't support this natively, but most DBs have some bitwise operator support and you can use the extra function for now. For example, this query will select CheeseShop models that have the 'Gouda' in its cheeses field.
`CheeseShop.objects.all().extra(where=['cheeses | %s = cheeses'], params=[CHEESES.index('Gouda')])`
Requires the M2Crypto module. See [http://sandbox.rulemaker.net/ngps/m2/howto.smime.html](http://sandbox.rulemaker.net/ngps/m2/howto.smime.html) for more information on using M2Crypto to create S/MIME email. This could also be adapted to allow signing, or sign+encrypt, but currently only encrypts.
Use just like `EmailMessage`, except takes an extra parameter `cert`, which is the path to the recipient's public X.509 certificate.
A file storage which uses a more sane rename method for existing files.
Add `DEFAULT_FILE_STORAGE = 'site.storage.BetterNameFileSystemStorage'` (obviously changing `site.storage` to the module which you put this inside)
With this, you can group form fields very easily. Since it does not create any html, you can use it not only to create fieldsets (with tables, lists, etc).
Includes the Javascript for Google Analytics. Will not show Google Analytics code when DEBUG is on or to staff users.
Use {% googleanalyticsjs %} in your templates.
You must set something like
GOOGLE_ANALYTICS_CODE = "UA-1234567-1"
in your settings file.
Assumes 'user' in your template variables is request.user, which it will be if you use:
return render_to_response('template.html',{ }, context_instance=RequestContext(request))
(Assuming django.core.context_processors.auth is in TEMPLATE_CONTEXT_PROCESSORS, which it is by default)
Reworked version of [this snippet](http://www.djangosnippets.org/snippets/205/) that now accepts an argument so the user can specify which tags to allow, and which attributes should be allowed for each tag. Argument should be in form `tag2:attr1:attr2 tag2:attr1 tag3`, where tags are allowed HTML tags, and attrs are the allowed attributes for that tag.
It also uses code from [this post on stack overflow](http://stackoverflow.com/questions/16861/sanitising-user-input-using-python) to add XSS protection.
Put this in an __init__.py somewhere that will be executed on initialization and all errors will be printed out to stderr. Useful for debugging Facebook apps, javascript calls, etc.
Integrating [reCAPTCHA](http://recaptcha.net/) with Django.
**Warning**: although *remoteip* is used as optional parameter in this snippet, it is likely to become mandatory in the future. Please see [the comment by Jim Garrison](http://www.marcofucci.com/tumblelog/26/jul/2009/integrating-recaptcha-with-django/#comment-262) for more detail.
Generic version of [this snippet](http://www.djangosnippets.org/snippets/433/).
1. Register on [reCAPTCHA](http://recaptcha.net/) to get your public/private key pair
2. Add your keys in settings.py
3. Add [recaptcha-client](http://pypi.python.org/pypi/recaptcha-client) to your project
4. Put ReCaptchaField and ReCaptcha widget somewhere (I've used a generic app `marcofucci_utils`)
5. Configure your form
More information on my website [marcofucci.com](http://www.marcofucci.com/tumblelog/26/jul/2009/integrating-recaptcha-with-django/).
I wanted to be able to limit which types of requests a view will accept. For instance, if a view only wants to deal with GET requests.
@methods(GET)
def index(request):
# do stuff
Now, calling this view with a non-GET request will cause a 403.
You can easily change this to a 404, by using a different return function: which you may wish to do with openly available sites, as a 403 indicates there is a resource present.
Based on [this snippet](http://www.djangosnippets.org/snippets/876/). More clean, with links to the related admin forms.
Nice example on customization of contributed django admin apps.
It adds the following to the user list interface: fields for is_superuser and is_staff, last login time; by default, short names of groups user is in (mousehover to see full names) It adds the following to the to group list interface: list of users in your groups.
To enable, just put it somewhere and import it from your main urls.py: import utils/admin_auth.py
This is a custom widget for displaying a view only date field in the django admin.
I used it to get around this ticket:
[http://code.djangoproject.com/ticket/342](http://code.djangoproject.com/ticket/342)
Provides a basic implementation of Yahoo's [MediaRSS](http://video.search.yahoo.com/mrss) format for [Photologue](http://code.google.com/p/django-photologue/) galleries
Simplest usage:
I have feedgenerator.py in a utils directory. Import photofeeds and hook up the feed url in your URLConf:
from utils.feedgenerator import photofeeds
urlpatterns += patterns('',
url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': photofeeds}),)
Without customization, this will generate a feed for the gallery archive at
`/feeds/gallery/`
It will contain a single photo per gallery, as returned by Gallery.sample()
Additionally, each gallery has a dynamic feed available at the url via Gallery.title_slug:
`/feeds/gallery/gallery-title-slug/`
This feed will contain an Item for each Photo in the Gallery
All that is left is to add an autodiscovery feed to your pages in <head>. An RSS agent like CoolIris can then parse your gallery and provide a slick view of your photos.
e.g Add something like this to gallery_detail.html:
`<link rel="alternate" href="/feeds/gallery/{{ object.title_slug }}/"
type="application/rss+xml" title="Photologue Gallery - {{ object.title }}" id="gallery_feed" />
`