If you're using [Django granular permissions](http://code.google.com/p/django-granular-permissions/), this templatetag may be useful.
It enables you to check permission in templates, as mentioned in the code:
{% has_row_perm user object "staff" as some_var %}
{% if some_var %}
...
{% endif %}
To be used in `if` statements, it always saves the result to the indicated context variable.
Put the snippet in row_perms.py in yourapp.templatetags package, and use `{% load row_perms %}` at your template.
A lot of times we need to insert a specific **CSS class** into a Form instance for it to be rendered in the template.
The current method is to specify the CSS class in the Python code through the form field widget. But it would be easier for the designer to be able to specify the CSS class in the template directly.
For example rather than doing this in your Python code:
'name = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))`
You can do this in your template:
`{{ form.name|cssclass:"special"}}`
This template filter only works with Form Field instance.
A {% mailto %}{% endmailto %} template tag that requires an e-mail destination and optionally accepts subject, cc and bcc. It will then wrap whatever is within the tag in an `<a href="mailto:..."> </a>` HTML tag.
See the docstring in the code for the {% mailto %} usage and some examples.
You will need to load this template tag to your template. You can find detailed instructions [here](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#code-layout). But in a nutshell:
1. Create a templatetags package (meaning a directory with a __init__.py file in it) on the same level as your application's model.py
2. Put the code for this tag in a module (example: extra_tags.py)
3. On your template use {% load extra_tags %} -- note: the app where the templatetags package was created needs to be in INSTALLED_APPS
4. Use {% mailto user.email 'You subject here for {{user.get_full_name}}' %}blah{% endmailto %}
This is my first django template tag. I am also NOT tremendously experienced with Python. Criticism and corrections are more than welcome.
This example shows, how to use database views with django models. NewestArticle models contains 100 newest Articles. Remember, that NewestArticle model is read-only. Tested with mysql.
This is a custom form-field designed to make those optional "enter a discount code" fields a little easier to deal with. You create one like this:
code = CodeLookupField(model=MyModel, field_name='slug', max_length=20)
And then when you validate your form, cleaned_data['code'] will be the actual object if anything was retrieved, or None if the user entered a bad piece of data.
If, like me, you've had trouble installing the [Python Imaging Library](http://www.pythonware.com/products/pil/) or [FreeType](http://freetype.sourceforge.org), you may have also had trouble getting a captcha to work. Here's my quick and dirty workaround — be warned, this is _very_ low level security, and shouldn't be used on high-profile sites.
Originally published at <http://gregbrown.co.nz/code/django-captcha-without-freetype-or-pil/>
Credit to the author of [django-simple-captcha](http://code.google.com/p/django-simple-captcha/), from whom I borrowed most of this code.
### Usage
from django import forms
from ABOVE-FILE import CaptchaField
class CaptchaTestForm(forms.Form):
myfield = forms.TextField()
security_check = CaptchaField()
This is another partial tag, taken from a previous partial tag.
The previous one assumed template locations by hardcoding in "partials/%s", etc. I took all that out, and made it work. And I took out the not needed third parameter for passing in your own data
So now you call like this:
{% partial "partials/mypartial.html" %}
It passes the template context var into the partial, so anything you do in the main template, will work in the partial
Just make sure you've got all the right imports.
At the [Internet Identity Workshop](http://iiw.idcommons.net/Iiw8) in May, 2009, I spoke to Alan Karp and Tyler Close of HP Labs about their research on authorization without identity. Here are my [Delicious links](http://delicious.com/sbwms/ZBAC) on the subject.
This led me to write code to generate a "web-key," the shared secret needed to implement the access control method discussed.
In his paper, Tyler Close recommends 70 bits for the shared secret, encoded as a 13-character Base32 string. I used 72 bits, so the secret is a 12-character, URL-safe Base64 string without padding characters.
I'm new to Python and Django, so I welcome refinements!
This object stitches together the [Babel](http://babel.edgewall.org/) number formating and the Decimal object, with a little of my own hand rolled validation for parsing.
Note the comment at the end of the code. It contains two lines to add to your settings.py.
CURRENCY_LANGUAGE_CODE = 'pt_BR'
CURRENCY_CODE = '' # If one exists like 'USD', 'EUR'
UPDATE 06-03-2009: Now with rounding
UPDATE 07-14-2009: Now with - More graceful handling of missing settings variables - Support for negatives (small oversight) - More flexible format strings - Thorough doctest tests
UPDATE 07-30-2009: Added the parse_string argument to the `__new__()` method. This fixes a bug when importing data using `manage.py loaddata`. I have not yet updated the tests to reflect the change.
The rest of the series: [Currency Widget](http://www.djangosnippets.org/snippets/1526/), [Currency Form Field](http://www.djangosnippets.org/snippets/1527/), [Currency DB Field](http://www.djangosnippets.org/snippets/1528/), [Admin Integration](http://www.djangosnippets.org/snippets/1529/)
This Field, Widget and the three lines of code in the form's clean method allow an easy (and hopefully general) way to add simple, unchangable text to a form.
Example use:
class OnlyTextForm(forms.ModelForm):
points = StaticField(label=_('Points'))
reviewer = StaticField(label=_('Reviewer'))
def clean(self):
for name, field in self.fields.items():
if isinstance(field, StaticField):
self.cleaned_data.update({name: self.initial[name]})
return self.cleaned_data
I was in need to have pluggable components that all have more or less some media files. I didn't want to pollute my config with dozens of media paths so I wrote this custom command that copies contents `<appdir>/app_media` to your `MEDIA_ROOT/<appname>` path.
In template you will refer your media files like `{{MEDIA_URL}}/appname/<path to media>`
A simple template filter for breaking a list into sublists of a given length, you might use this on an ecommerce product grid where you want an arbitrary number of rows of fixed columns. Unlike the other partitioning filters I've seen, this doesn't try to distribute the rows evenly, instead it fills each row for moving onto the next.
This filter preserves the ordering of the input list.
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.