JSON Encoder for models
A simplejson encoder that knows how to encode django models, and it's little brother that also know how to deals with lazy translations.
- models
- json
- encoding
A simplejson encoder that knows how to encode django models, and it's little brother that also know how to deals with lazy translations.
Wrote this some time ago when I couldn't find one already completed. Came up in the IRC channel so I decided to post it. Easy enough to use. `from ssldecorator import ssl_required` `@ssl_required` `def your_view(request):` ` ''' your code here '''` You can place a variable in your settings.py to change the SSL domain (ie, if you have SSL running on secure.yourdomain.com instead of www.yourdomain.com).. `SSL_DOMAIN = 'https://secure.yourdomain.com'` Note: please include a proper URL. If https isn't used, the decorator will add it.
Pass in a date and you get a humanized fuzzy date diff; e.g. "2 weeks ago" or "in 5 months". The date you pass in can be in the past or future (or even the present, for that matter). The result is rounded, so a date 45 days ago will be "2 months ago", and a date 400 days from now will be "in 1 year". Usage: * `{{ my_date|date_diff }}` will give you a date_diff between `my_date` and `datetime.date.today()` * `{{ my_date|date_diff:another_date }}` will give you a date_diff between `my_date` and `another_date` Make sure to install this as a template tag and call `{% load date_diff %}` in your template; see the [custom template tag docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) if you don't know how to do that.
Sometimes you need to write a tag that renders other template, but the template name depends on template tag arguments. Usually you use simple_tag or write your own Node class. Here is a simple aproach that uses inclusion_tag. This way you can use context objects when used with takes_context=True
create an instance of this class: `rpcserver = XMLRPC()` then define handlers on it with the register decorator: @rpcserver.register("pingback.ping") def handle_pingback(sourceURI, targetURI) # ... de-serialization of the arguments and serialization of the return values is handled by the XMLRPC object, so just expect python built-in types as your arguments and use them as your return values. you can also raise instances of xmlrpclib.Fault from within your handlers and a proper xmlrpc fault will be sent out as the response. then you can use `rpcserver.view` in your urlconf to offer up your XML-RPC service at a URL: urlpatterns = patterns('', url(r'^$', rpcserver.view, name="xmlrpc"), # ... )
Simple debug middleware that uses [pycallgraph](http://pycallgraph.slowchop.com) to get a visual representation of the call graph, including number of calls and execution times. Usage: 1. Replace *myapp* in the snippet with the name of your application and or adjust include and exclude according to your needs 2. Add CallgraphMiddleware to your middlewares in settings.py 3. Append ?prof to any URL in your application to trigger the callgraph creation Each callgraph cerated will be named callgraph-*timestamp*.png. This is because multiple callgraphs will be created when a re-direction occurs for example.
Class DatabaseStorage can be used with either FileField or ImageField. It can be used to map filenames to database blobs: so you have to use it with a **special additional table created manually**. The table should contain: *a pk-column for filenames (I think it's better to use the same type that FileField uses: nvarchar(100)) *a blob column (image type for example) *a size column (bigint type). You can't just create blob column in the same table, where you defined FileField, since there is no way to find required row in the save() method. Also size field is required to obtain better perfomance (see size() method). So you can use it with different FileFields and even with different "upload_to" variables used. Thus it implements a kind of root filesystem, where you can define dirs using "upload_to" with FileField and store any files in these dirs. Beware saving file with the same "virtual path" overwrites old file. It uses either settings.DB_FILES_URL or constructor param 'base_url' (@see __init__()) to create urls to files. Base url should be mapped to view that provides access to files (see example in the class doc-string). To store files in the same table, where FileField is defined you have to define your own field and provide extra argument (e.g. pk) to save(). Raw sql is used for all operations. In constractor or in DB_FILES of settings.py () you should specify a dictionary with db_table, fname_column, blob_column, size_column and 'base_url'. For example I just put to the settings.py the following line: DB_FILES = {'db_table': 'FILES', 'fname_column': 'FILE_NAME', 'blob_column': 'BLOB', 'size_column': 'SIZE', 'base_url': 'http://localhost/dbfiles/' }" And use it with ImageField as following: player_photo = models.ImageField(upload_to="player_photos", storage = DatabaseStorage() ) DatabaseStorage class uses your settings.py file to perform custom connection to your database. The reason to use custom connection: http://code.djangoproject.com/ticket/5135 Connection string looks like "cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')" It's based on pyodbc module, so can be used with any database supported by pyodbc. I've tested it with MS Sql Express 2005. Note: It returns special path, which should be mapped to special view, which returns requested file: **View and usage Example:** def image_view(request, filename): import os from django.http import HttpResponse from django.conf import settings from django.utils._os import safe_join from filestorage import DatabaseStorage from django.core.exceptions import ObjectDoesNotExist storage = DatabaseStorage() try: image_file = storage.open(filename, 'rb') file_content = image_file.read() except: filename = 'no_image.gif' path = safe_join(os.path.abspath(settings.MEDIA_ROOT), filename) if not os.path.exists(path): raise ObjectDoesNotExist no_image = open(path, 'rb') file_content = no_image.read() response = HttpResponse(file_content, mimetype="image/jpeg") response['Content-Disposition'] = 'inline; filename=%s'%filename return response **Warning:** *If filename exist, blob will be overwritten, to change this remove get_available_name(self, name), so Storage.get_available_name(self, name) will be used to generate new filename.* For more information see docstrings in the code. Please, drop me a line if you've found a mistake or have a suggestion :)
This snippet adds simple partial support to your templates. You can pass data to the partial, and use it as you would in a regular template. It is different from Django's `{% include %}`, because it allows you to pass a custom variable (context), instead of reusing the same context for the included template. This decouples the templates from each other and allows for their greater reuse. The attached code needs to go into `templatetags` folder underneath your project. The usage is pretty simple - `{% load ... %}` the tag library, and use `{% partial_template template-name data %}` in your template. This will result in template passed as **template-name** to be loaded from **partials** folder. The **.html** extension will be appended to the file name. The file has to be in one of template paths accessible to the loader) and rendered with **data** as its context. The data is available in the template as an `item` context variable. You can find more information in the [relevant Django documentation](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags)
This is the "unobtrusive comments moderation" code from http://www.djangosnippets.org/snippets/112/ , but updated so it works properly with Django 1.0. There are only a few small changes reflecting changes in the comments, contenttypes, and signals APIs. For full background, see the original snippet: http://www.djangosnippets.org/snippets/112/
Provides two template tags to use in your HTML templates: breadcrumb and breadcrumb_url. The first allows creating of simple url, with the text portion and url portion. Or only unlinked text (as the last item in breadcrumb trail for example). The second, can actually take the named url with arguments! Additionally it takes a title as the first argument. This is a templatetag file that should go into your /templatetags directory. Just change the path of the image in the method **create_crumb** and you are good to go! Don't forget to `{% load breadcrumbs %}` at the top of your html template! [http://drozdyuk.blogspot.com/2009/02/dagood-django-breadcrumbs.html](http://drozdyuk.blogspot.com/2009/02/dagood-django-breadcrumbs.html)
Template filter to hide an email address away from any sort of email harvester type web scrapers and so keep away from spam etc. The filter should be applied on a string which represents an email address. You can optionally give the filter a parameter which will represent the name of the resulting email href link. If no extra parameter is given the email address will be used as the href text. {{ email|mungify:"contact me" }} or {{ email|mungify }} The output is javascript which will write out the email href link in a way so as to not actually show the email address in the source code as plain text. Also posted on [my site](http://www.tomcoote.co.uk/DjangoEmailMunger.aspx).
This uses the Really Simple Color Picker in jQuery: http://www.web2media.net/laktek/2008/10/27/really-simple-color-picker-in-jquery/ Get source from there or GitHub: http://github.com/laktek/really-simple-color-picker/tree/master
This template tag takes the current GET query, and modifies or adds the value you specify. This is great for GET-query-driven views, where you want to provide URLs which reconfigure the view somehow. **Example Usage:** `{% get_string "sort_by" "date" %}` returns `all=your¤t=get&variables=plus&sort_by=date`
This was a wild experiment, which appears to work! One model holds all the data, from every object version ever to exist. The other model simply points to the latest object from its gigantic brother. All fields can be accessed transparently from the little model version, so the user need not know what is going on. Coincidently, Django model inheritance does exactly the same thing, so to keep things insanely simple, that's what we'll use: class EmployeeHistory(FullHistory): name = models.CharField(max_length=100) class Employee(EmployeeHistory): pass That's it! Django admin can be used to administer the `Employee` and every version will be kept as its own `EmployeeHistory` object, these can of course all be browsed using the admin :-) This is early days and just a proof of concept. I'd like to see how far I can go with this, handling `ForeignKey`s, `ManyToManyField`s, using custom managers and so on. It should all be straightforward, especially as the primary keys should be pretty static in the history objects... *updated 3 August 2009 for Django 1.1 and working date_updated fields*
a randomized version of {% include %} {% rand_include "foo.html","bar.html","zot.html" %}
3110 snippets posted so far.