This FloatField replacement allows users to enter math expressions, such as:
4/5 + sqrt(32)
And will evaluate them safely when the field's clean() function is called. In the example above, it will evaluate to a float value of about 6.457.
Reference:
[http://lybniz2.sourceforge.net/safeeval.html](http://lybniz2.sourceforge.net/safeeval.html)
The available functions are listed herein. Note that the from __future__ import division causes integer division expressions to be evaluated as floats. For example "1/2" evaluates as 0.5 when it would otherwise have evaluated to 0 (assuming Python 2.X).
Allows you to dynamically maintain a local_constants.py file from a migration tool like South. Example of usage:
set_constant('/home/projects/sample/local_constants.py', 'STAMP_MW_ID', 42, 'Set from sample.0007_add_constants.py')
More more information, see [Allows you to dynamically maintain a local_constants.py file from a migration tool like South. Example of usage:
set_constant('/home/projects/sample/local_constants.py', 'STAMP_MW_ID', 42, 'Set from sample.0007_add_constants.py')
More more information, see [http://menendez.com/blog/maintain-contants-through-south-data-migration/](http://menendez.com/blog/maintain-contants-through-south-data-migration/).
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.
Background
==========
Two years ago, Malcolm Tredinnick put up an excellent post about doing dynamic Django forms. There have been several excellent write-ups on it since - Google is your friend.
One year ago, I attempted to make a dynamic Formset - see [this snippet](http://www.djangosnippets.org/snippets/1290/). Malcolm posted a cleaner solution two weeks later, and I liked his solution better. Some time after that happened, his site tanked.
I'm re-posting my snippet using his technique, so that everyone can see how it is done. Credit to goes to Malcolm - I'm just the messenger. If his site ever comes back up , check out his complex formset post [here](http://www.pointy-stick.com/blog/2009/01/23/advanced-formset-usage-django/).
I'll use Malcolm's example code, with as few changes as possible to use a formset. The models and form don't change, and the template is almost identical.
I won't reproduce all of Malcolm's code - I'm just show the form setup. There are no models here - you'll have to use your imagination for Quiz, Question, and Answer models. He did some fancy validation as well - I'm not going to here.
Problem
=======
Build a formset based on dynamically created forms.
Solution
========
The core idea in this code is found in the `_construct_form` method. Typically, this is where a formset makes new forms - it handles indexing them so that everything is nice and unique. We can take advantage of this by overriding the method and inserting a `kwarg` that will be passed on to our form class, then calling the parent `_contruct_form` method to let it finish doing everything else for us. This is what Malcolm, a core Django developer, knows about, and I, a random Django user, typically do not.
Code
====
This pattern greatly simplifies building formsets dynamically, and it really only requires a few bits of knowledge.
1. If we `pop()` special arguments out of `kwargs` dictionaries, we then can pass the remaining `kwargs` along to parent methods and let them do the rest of the setup for us. See code tricks #1 and #3.
2. If we have a form and need to add dynamic fields that we didn't declare the usual way, we can just add them to the `self.fields` dictionary. See code trick #2.
3. If we need to add forms dynamically to a formset, we can use the `self.extra` variable to specify how many we want, based on the length of a custom queryset. See code trick #4.
4. If we want to pass some special arguments to a form that will be part of a formset when it is constructed, we can add them to the `kwargs` dict in `_construct_form`, taking advantage of the `index` variable to track which object from our queryset we wanted. See code trick #5.
Sometimes, when you're working on improving one specific aspect of your site, it's easier to browse your code by type than by application. E.g. you want quick access to all admin.py files because you're improving or customizing your admin site across the board and not for a specific app. This little management command adds a shortcuts dir to your project root that contains a bunch of symlinks to your code, organized in subdirs by type of code.
You'll have to put this in `/management/commands/make_shortcuts.py` under an app of your choice. Usage: `python manage.py make_shortcuts`. Don't forget to ignore the /shortcuts directory in your source code management software.
Model field that stores serialized value of model class instance and returns deserialized model instance. Example usage:
from django.db import models
import SerializedObjectField
class A(models.Model):
object = SerializedObjectField(serialize_format='json')
class B(models.Model):
field = models.CharField(max_length=10)
b = B(field='test')
b.save()
a = A()
a.object = b
a.save()
a = A.object.get(pk=1)
a.object
<B: B object>
a.object.__dict__
{'field': 'test', 'id': 1}
Based fully on [snippet 1929](http://www.djangosnippets.org/snippets/1929/)
**The update is:**
It checks to see the view returns an instance of HttpResponse and returns that rather than trying to render it.
This allows you to return something like `HttpResponseRedirect('/')`, or use a normal `render_to_response` to use a different template.
*Also updates cleandict as per comment on original snippet*
In this case the 'render_template' decorator assumes there is a myview.html template. this keeps things simple and you DRY. Hope it helps.
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.
While checking up on some cronjobs at [YouTellMe](http://www.youtellme.nl/) we had some problems with large cronjobs that took way too much memory. Since Django normally loads all objects into it's memory when iterating over a queryset (even with .iterator, although in that case it's not Django holding it in it's memory, but your database client) I needed a solution that chunks the querysets so they're only keeping a small subset in memory.
Example on how to use it:
`my_queryset = queryset_iterator(MyItem.objects.all())
for item in my_queryset:
item.do_something()`
[More info on my blog](http://www.mellowmorning.com/2010/03/03/django-query-set-iterator-for-really-large-querysets/)
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).
I wasn't sure if my setup supported sessions properly. This view helped me make sure.
Usage: fill the inputs with text and make sure that these values traverse a couple of requests. If it doesn't work then maybe the session backend you've set is broken?
I'm using this to store settings in a thread-safe manner on mod_wsgi multithread deployment.
The idea is to import
`from localsettings import localsettings`
instead of doing
`from django.conf import settings`
and use it as you would use normal settings, with the difference that you can alter settings for the current thread with a middleware (think of altering SITE_ID).
Warning: altering settings is not officially supported and can lead to thread problems.