**Disclaimer**
This is proof of concept snippet, It can not be considered as best practice. Seems like it's better to store (key => value) in sepetare model with 'key' and 'value' fields.
**Example**
You can assign any dict to model field that can be dumped/serialized with Django json encoder/decoder. Data is saved as TextField in database, empty dict is saved as empty text. Tested with Django 1.2beta.
import DictionaryField
class UserData(models.Model):
user = models.ForeignKey(User)
meta = DictionaryField(blank=True)
There are similar snippets: [JSONField 1](http://www.djangosnippets.org/snippets/377/) or [JSONField 2](http://www.djangosnippets.org/snippets/1478/).
Sometimes we need to build a ChoiceField from data in a Model or more than just one model via fk's but the ModelChoiceField is not *that* flexible. So, in order to obtain a list of tuples with pk and a descriptive text for the choices parameter of the ChoiceField use this little function.
Put this in a base.py file.
And config this settings:
DATABASE_ENGINE = 'path.to.module.with.base.file'
DATABASE_STATEMENT_TIMEOUT = 60000 # milliseconds
(Idea from: http://www.mailinglistarchive.com/html/[email protected]/2009-02/msg00024.html)
This is a quick hack to address the SSL info leakage covered here:
http://www.freedom-to-tinker.com/blog/felten/side-channel-leaks-web-applications
Don't use this in prod without testing. :-)
I'll get some feedback from django-dev and update here.
In principle it's a DRY code of a template node that can be used for creating project-wide template-tags. These can be used to display conceptually common blocks in templates with applications specific looks and content. E.g.:
1. application-specific info message,
2. model instances details in the list context,
3. login messages like 'Please login or signup to [some app-dependent text]' with appropriate url's,
4. standard forms (e.g with same CSS classes, displayed with uni_form).
The code is profusely commented so look it up for details. Basically, when you have your project-wide `SubIncludeNode` tag defined, then just define appropriately named templates in applications template subdirectories e.g. `'profiles/_show_item.html'`.
** Example usage: login or signup message **
Let's say we are editing template rendered by the view indicated by the pattern named 'project_list' in the 'projects' app:
{# those are equivalent #}
{% login_or_signup %}
{% login_or_signup project_list %}
{% login_or_signup "project_list" %}
{# academic purposes direct sub_include usage #}
{# those two includes are also equivalent if there is no template called '_login_or_signup.html' in the 'projects' subdirectory #}
{% url acct_signup as signup_url %}
{% url acct_login as login_url %}
{% url project_list as next_url %}
{% sub_include "_login_or_signup.html" %}
{% include "_login_or_signup.html" %}
{# and those two are also equivalent if there is a template called '_login_or_signup.html' in the 'projects' subdirectory #}
{% sub_include "_login_or_signup.html" from "projects" %}
{% sub_include "_login_or_signup.html" %}
{# also equivalent include if there is no variable called 'projects' in tempalte's context #}
{% sub_include "_login_or_signup.html" from projects %}
{# those are examples of using custom subcontext #}
{% url acct_signup as signup_url %}
{% url acct_login as login_url %}
{% sub_include "_login_or_signup.html" from "default" with login_url,signup_url,next_url="/welcome" %}
{% sub_include "_login_or_signup.html" with login_url="/login",next_url="/welcome",signup_url="/signup" %}
** Mored advanced usage proposal **
Say you have an subclasses of some model from the original app in a separate extending apps. You want to display subclasses instances differently using the original app templates. In the original app you do not know what the set of subclasses is (as the original app is not aware of the extending apps). Subclassing the `SubIncludeNode` you can override the `default_subdir` method such that it returns the app label of a model instance that was passed as a argument of your tag. This way you just put templates like `_show_instance.html` in extending apps subdirectories and voila - you have implementation of the overrideable templates displaying appropriately details about the model subclass instances.
A simple django-admin filter to allow a boolean-like filter for IS NULL/IS NOT NULL.
By default it applies to CharField, IntegerField, and FileField, but you can change this by editing NullFilterSpec.fields.
Based on #1381
Use this piece of code to add IPv4/IPv6 and network support to Django.
An IPAddressField allows you to find IP's for a given subnet. An IPNetworkField allows you to find a subnet for a given IP or find a subnet within a subnet.
For starters, simply paste it into a new file in your app called fields.py.
IPAddressField example
# models.py
from fields import IPAddressField
class IPTest(models.Model):
ip = IPAddressField()
To search for an IP within a given subnet
from ipaddr import IPNetwork
IPTest.objects.filter(ip__in=IPNetwork('10.0.0.0/24'))
IPNetworkField example
# models.py
from fields import IPNetworkField, IPNetworkQuerySet
class IPTest(models.Model):
objects = IPNetworkQuerySet.as_manager()
network = IPNetworkField()
To search for a subnet with a given IP
from ipaddr import IPAddress
IPTest.objects.network('network', IPAddress('10.0.0.1'))
I was looking for a way to save screen real estate, by using icons instead of labels for my list of choices, which in addition should be displayed as horizontal radio buttons.
For example, I wanted to use thumbs_up.gif instead of "approve".
I found a HorizontalRadioRenderer here:
[https://wikis.utexas.edu/display/~bm6432/Django-Modifying+RadioSelect+Widget+to+have+horizontal+buttons](https://wikis.utexas.edu/display/~bm6432/Django-Modifying+RadioSelect+Widget+to+have+horizontal+buttons)
Thanks to Barry McClendon for this snippet!
At first, I tried to achieve display of icons instead of labels by modifying the render method, but after a while I gave up on that and decided to just use the choices tuple.
This doesn't work too well with a select box (no icons, no text), but in combination with a radio widget it looks quite nice.
If you mark the strings for translation, you can also easily change icons, alt and title for each language.
The inbuilt test client can be used to only test single domain applications ie no support for supplying absolute URLs.
But there are cases where one might like to test against URL rewrites, external domains/services like OpenID, OAuth etc.
This client has an external dependency on httplib2, to maintain the sessions (cookie-based). The API is exactly similar to the inbuilt test client.
>>> from client import TestClient
>>> c = TestClient()
>>> resp = c.get("http://www.google.com/")
>>> resp.status_code
200
**Note**: Unlike the built-in test client, this test client cannot access the template and context attributes from the response even if testing a local application.
This is a piece of middleware that reports the logged-in user back to Apache. This should cause the logged-in user to be present in the apache access log.
Put it in `settings.MIDDLEWARE_CLASSES` after `AuthenticationMiddleware`.
This has been tested with mod_python but does [not work with wsgi](http://groups.google.com/group/modwsgi/browse_thread/thread/8785a99d4ba7ee99).
The popular [django-tagging](http://code.google.com/p/django-tagging/) app has, in its implementation and semantics, a highly usable and transparent elegance -- but then you have to call methods on a Tag instances' items collection. These classes let you inline the tag name in the chain of queryset filter methods instead.
TO USE:
### models.py
...
from tagging.fields import TagField
from tagging.models import Tag as Tag
class YourModel(models.Model):
...
yourtags = TagField()
objects = TaggedManager()
...
### and then elsewhere, something like--
...
ym = YourModel.objects.order_by("-modifydate")[0]
anotherym = YourModel.objects.get(id=7) ## distinct from ym
ym.yourtags = "tag1 tag2"
anotherym.yourtags = "tag1 othertag"
ym.save()
anotherym.save()
with_tag1 = YourModel.objects.tagged('tag1')
with_tag2 = YourModel.objects.tagged('tag2').order_by('-modifydate')
print ym in with_tag1 ## True
print anotherym in with_tag1 ## True
print ym in with_tag2 ## False
... since these are QuerySets, you can easily create unions (e.g. `with_tag1 | with_tag2` and othersuch) as you need and filter them to your hearts' content, without having to instantiate Tag all the time (which you can of course do as well).
A replacement for sending mail that takes the name of a template which exists in both text and html formats, and uses these to create a multipart email populated with the given context.
I found [snippet #1016](http://www.djangosnippets.org/snippets/1016/) while looking for a way to add a button to the top of an admin change form, and it didn't work. I found that it used the old admin, so I updated it to django 1.1.1
By using this simple wrapper instead of Django's default send_mail function, you gain the peace of mind of knowing that when settings.DEBUG == True, all the emails will be sent to you instead of the original recipient. Handy for testing.
For a model FK'd to a user or profile, you might want every instance of that thing to appear in your site and in the admin as say "Joe's bucketlist." But if Joe's name is Ross, you want "Ross' bucketlist", not "Ross's bucketlist."
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.