You can use this cache backend to cache data in-process and avoid the overhead of pickling. Make absolutely sure you don't modify any data you've stored to or retrieved from the cache. Make deep copies instead if necessary.
The backend is basically identical to Django's stock locmem cache (as of r15852 - after 1.3rc1) with pickling removed. It has been tested with that specific Django revision, so basically it's >=1.3 compatible.
See [Django ticket #6124](http://code.djangoproject.com/ticket/6124) for some background information.
TimeZoneField is not supported with South 0.7. This snippet adds a custom rule to the introspection rules for TimeZoneField. The code is found in the following thread, and fixed according to the latest version of TimeZoneField.
http://groups.google.com/group/south-users/browse_thread/thread/34a05331140ee4dd
**Usage**
Simplest way is to save this snippet in a south_rules.py file and add an import in the models.py.
FastCGI handler in prefork mode first imports every application, then forks. If any application during import opens connection to database, open connection is inherited by all of child processes; open db connection cannot be shared between processes, and if one process sends a request, another can receive a reply; also, if one process closes it, others have a desynchronized database handle.
See:
* http://stackoverflow.com/questions/1573579/psycopg2-disconnects-from-server
* http://stackoverflow.com/questions/393637/django-fastcgi-randomly-raising-operationalerror
* http://code.djangoproject.com/ticket/13215
* http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48
If you put this snippet in your project-level __init__.py, then running manage.py runfcgi will fail loudly if the database connection is open in the parent process. This will happen only when you provide debug=true option to runfcgi to avoid monkey-patching code that runs in production mode.
**NOTE: This is modified from 1.0's test runner and has only been tested on Django 1.0 + Python 2.5**
This is a test runner that searches inside any app-level "tests" packages for django unit tests. Modules to be searched must have names that start with "test_" (this can be changed by modifying `get_multi_tests()`, [`mod.startswith('test_') and mod.endswith('.py')`]).
It also allows for arbitrarily nested test packages, with no restrictions on naming, so you could have:
myapp/
+- tests/
+- __init__.py
+- test_set1.py
+- category1/
+- __init__.py
+- test_something.py
+- subcat/
+- __init__.py
+- test_foobar.py
+- category2/
+- __init__.py
+- test_other.py
and "manage.py test myapp" would pick up tests in all four test_*.py test modules.
Searching the modules in this way, instead of importing them all into the top-level `__init__.py`, allows you to have "name collisions" with TestCase names -- two modules can each have a TestFooBar class, and they will both be run. Unfortunately, this snippet doesn't allow you to specify a full path to a specific test case or test module ("manage.py test myapp.category1.test_something" and "manage.py test myapp.test_set1.TestFooBar" won't work); using "manage.py test myapp.TestFooBar" will search out all test cases named "TestFooBar" and run them. "manage.py test myapp.TestFooBar.test_baz" will work similarly, returning the test_baz method of each TestFooBar class.
To use, put this code in "`testrunner.py`" in your project, and add `TEST_RUNNER = 'myproject.testrunner.run_tests'` to your `settings.py`.
Other approach of making middleware. Advantage of is to specify, which middleware is used for which view function and in what order. Middleware function gets all arguments, that are passed to view function.
**Example usage**
@RequestMiddleware
def print_params_middleware(request, *args, **kwargs):
print 'GET params:', request.GET
@ResponseMiddleware
def modify_headers_middleware(request, response, *args, **kwargs):
response['Content-Type'] = 'text/html'
@ExceptionMiddleware
def catch_error_middleware(request, e, *args, **kwargs):
return HttpResponse('catched error %s' % e )
@modify_headers_middleware
@catch_error_middleware
@print_params_middleware
def some_view(request, *args, **kwargs):
print 'someview'
return HttpResponse()
This will truncate a long character based on the given length parameter. If the word is cut-off, it will return the string up until the next space. If there are no spaces in the next 5 characters, that should mean a very long word and we should truncate right away.
Manager Mixin to implement get_random() in your models.
You can override get_objects to tune the queriset
To use, define your class:
class MyManager(models.Manager, RandomObjectManager):
DEFAULT_NUMBER = 5 # I can change that
def get_objects(self):
return self.filter(active=True) # Only active models plz
class MyModel(models.Model):
active = models.BooleanField()
objects = MyManager()
Now you can do:
MyModel.objects.get_random()
This class makes easier the job of rendering lists of model instances in django templates. It's intended to mimic the behavior of the Model Forms in that it contains the code needed to render it as an HTML table and makes it easy to handle all the model lists from a single view (as it's usually done with the generic views for creating and updating model instances).
It also supports pagination and provides hooks for subclassing and customizing the rendered fields, column titles and list order.
Basic example:
`class Account(Model):`
`name = models.CharField(max_length=MAX_LENGTH)`
`responsible = models.CharField(max_length=MAX_LENGTH)`
`email = models.EmailField()`
`class AccountModelList(ModelList):`
`class Meta:`
`model = Account`
`fields = ['name', 'responsible'] #email won't get a column`
The model list would be instantiated with something like:
`model_list = AccountModelList(instances=account_queryset)`
Then a table header can be rendered with model_list.as_table_header(), while the table rows can be rendered calling as_table() on each model_list.items element.
This is useful for randomizing an iterable of objects in place in a django template. Usage:
{% load shuffle %}
{# now some_list is ordered #}
{% shuffle some_list %}
{# now some_list is randomized #}
Python includes (and [Django recommends](http://docs.djangoproject.com/en/dev/topics/email/?from=olddocs#testing-e-mail-sending)) a simple email debugging server which prints mail to stdout. The trouble is, unlike any half-competent mail reader, long lines are broken up, and thus long URLs don't work without modification.
This snippet simply unwraps long lines (broken by "=") so long URLs can be easily copied/pasted from the terminal.
Save this snippet into a file named "better.py" and execute it.
**Purpose**
We often need to store x,y, width and height for a model, we can store all these values in same field by having custom field.
**How to Use**
Save this code in *customfields.py* and in your model
>*from customfields import FrameField*
>*class MyModel(models,Model)*
>* frame = FrameField()*
And in your in views, you can use as follows
>*model = MyModel.objects.get(1)*
>*print model.frame.x, model.frame.y, model.frame.width, model.frame.height*
This is a slight modification from the original version at [http://djangosnippets.org/snippets/709/](http://djangosnippets.org/snippets/709/) and is a middleware designed to output the right headers for generated KML or KMZ content. In the case of KMZ content, it handles the compression of the original KML content into the KMZ format.
This version applies the processing to only requests ending with a .kml or .kmz in the URL. For instance, a request with the URL **http://example.com/kml/foo.kml** or **http://example.com/foo.kmz** will get processed by this middleware.
This is a small manager that just adds a "bulk_insert" function. This is very basic, I'm basically throwing it up here because it's simple and works for my current needs. Feedback on improvements (which I know would be a ton) are very welcome.
Some known "gotchas":
1. This doesn't handle relationships. If, however, you want to do one-to-one or foreignkeys you'll have to use the actual table column name ('whatever_id' typically)
2. When using this I typically make a bulk_insert call every 500 iterations or so
Some improvements that I think could be good:
1. Possibly just find the fields from the first object in the objs array and leave the fields argument as optional
2. Create a bulk_insert_from_file function and use LOAD DATA INFILE for mysql and whatever else supports it
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.