When using Amazon's ELB with SSL termination, Django needs to know that the requests are secure. You need to use the special indication given on the request (HTTP_X_FORWARDED_PROTO) to determine that. This middleware will do that for you.
The second part is forcing requests to HTTPS in case they are not. This part is not mandatory and could probably be done using configuration rules in your HTTP server. Note that I did it for the specific site, simply to avoid redirecting requests which are not of interest in the first place.
This snippet is based on work done in [Django-Heroism](https://github.com/rossdakin/django-heroism).
A pre_save signal that will automatically generate a slug for your model based on the "title" attribute, and will store the new slug in the "slug" attribute.
USAGE:
from django.db.models.signals import pre_save
from YOURPACKAGE import slug_generator
pre_save.connect(slug_generator, sender=YOURMODEL)
A very basic Basic Auth middleware that uses a username/password defined in your settings.py as `BASICAUTH_USERNAME` and `BASICAUTH_PASSWORD`. Does not use Django auth. Handy for quickly securing an entire site during development, for example.
In settings.py:
BASICAUTH_USERNAME = 'user'
BASICAUTH_PASSWORD = 'pass'
MIDDLEWARE_CLASSES = (
'app.module.BasicAuthMiddleware',
#all other middleware
)
This snippet uses the admin FilterSelectMultiple widget in normal forms.
Earlier I tried this without the **internationalization javascript** and failed, so I looked around the web and found couple of posts, they worked but suggest many customizations.
I learnt from them that they had this *jsi18n* javascript included. I included it with mine and it worked.
I have written a [detailed post](http://www.rohanjain.in/coding/2011/06/20/django-using-admin-horizontal-filter-in-forms/) about this.
This django field can be used to introduce Spanish national Identification Numbers (NIF). It validates the NIF format and checks if the last letter is correct.
It also validates NIE numbers for foreign people.
You can use the field in your own forms:
'code'
dni = DNIField(max_length=15, widget=forms.TextInput(), label=_('DNI'))
'code'
I wanted a simple way to display events for a given month in a calendar, so I adapted some code to write a template tag. `Event` is the model class, and it needs to have a `date_and_time` field. Each event is part of a `Series`, so in the view you can filter events by which series, or display events for all known Series.
[Full explanation and description of simple Django event calendar template tag](http://williamjohnbert.com/2011/06/django-event-calendar-for-a-django-beginner/).
[Chris' code](http://djangosnippets.org/snippets/1845/) adapted to django 1.3. Basicly E-mail authorisation backend.
Put it as one of your AUTHENTICATION_BACKENDS in settings.py:
AUTHENTICATION_BACKENDS = (
'community.auth.EmailBackend',
)
From: [incredible times](http://incredibletimes.org)
With inspiration from: [Unethical Blogger](http://unethicalblogger.com/2008/05/03/parsing-html-with-python.html)
This code parses any provided HTML content, and extracts a number of paragraphs specified, with all the content and tags inside them.
Example:
Template variable "content" contains:
<a href="#>some text</a>
<p><strong>Testing</strong>testing testing this is a tester's life</p>
<div>I wont see the world</div>
<p>Another paragraph</p>
So, place this code in any loaded template module (inside a templatetags folder of your app... i.e. myapp/templatetags/myutils.py)
{% load myutils %}
{{ content|paragraphs:"1"}}
Would return:
<p><strong>Testing</strong>testing testing this is a tester's life</p>
Whereas
{% load myutils %}
{{ content|paragraphs:"2"}}
Returns:
<p><strong>Testing</strong>testing testing this is a tester's life</p>
<p>Another paragraph</p>
I find Django's default YAML serializer output too repetitive, so I came up with this customized version that avoids outputting the model name for every single object, and makes the primary key into an index for the object's fields. This allows many simple model instances to be serialized as one-liners.
See the module docstring for additional explanation and usage notes.
Perhaps this is blindingly obvious but I spent a while trying to get this, before figuring out that when a each item of an iterated ValuesQuerySet is a dict.
Useful for serialising to JSON or XML etc.
HTML allows an option in a <select> to be disabled. In other words it will appear in the list of choices but won't be selectable. This is done by adding a 'disabled' attribute to the <option> tag, for example:
`<option value="" disabled="disabled">Disabled option</option>`
This code subclasses the regular Django Select widget, overriding the render_option method to allow disabling options.
Example of usage:
class FruitForm(forms.Form):
choices = (('apples', 'Apples'),
('oranges', 'Oranges'),
('bananas', {'label': 'Bananas',
'disabled': True}), # Yes, we have no bananas
('grobblefruit', 'Grobblefruit'))
fruit = forms.ChoiceField(choices=choices, widget=SelectWithDisabled())
Ordinarily, it is not possible to edit Group membership from the Group admin because the m2m relationship is defined on User. With a custom form, it is possible to add a ModelMultipleChoiceField for this purpose. The trick is to populate the initial value for the form field and save the form data properly.
One of the gotchas I found was that the admin framework saves ModelForms with commit=False and uses the save_m2m method when the group is finally saved. In order to preserve this functionality, I wrap the save_m2m method when commit=False.
This is a model that implements (most of) the python dictionary interface. Meaning, you can work with this model exactly like a python dictionary, and it handles querying the database for it's values, saving/deleting the helper objects, etc.
I wrote this originally when I needed to store an arbitrary dictionary in the database, and decided to work it up into a near-complete implementation of a dictionary.
In order to make sure that the dictionary is the most optimized possible, I have a static method that can be used for retrieval. Feel free to ignore it if you don't care about optimizing database queries.
Here's an example:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from binder.models import Dictionary
>>> d = Dictionary.getDict('Foobar')
>>> print d
{u'Foobar': u'omgbbq', u'HAHAHAH': u"who's afraid of a big, black, bat?"}
>>> d['pot'] = 'The kettle is black.'
>>> print d
{u'Foobar': u'omgbbq', u'pot': u'The kettle is black.', u'HAHAHAH': u"who's afraid of a big, black, bat?"}
>>> print d['pot']
The kettle is black.
>>> for k, v in d.iteritems():
... print k +":", v
...
Foobar: omgbbq
HAHAHAH: who's afraid of a big, black, bat?
pot: The kettle is black.
>>> print d.keys()
[u'Foobar', u'HAHAHAH', u'pot']
>>> print d.values()
[u'omgbbq', u"who's afraid of a big, black, bat?", u'The kettle is black.']
>>>
There's several more functions that I've implemented; check the code to see. (An interesting note: DictField saves immediately upon making a change, which is good to keep in mind in case that functionality isn't expected.)
Hope someone finds this useful. :)
--Chris