Login

All snippets

Snippet List

Dynamically change admin widgets at runtime

django-adminwidgetswap =============== adminwidgetswap is used for dynamically swapping out widgets from django's generated admin. This allows applications to be packaged generically without the need for WYSIWYG dependencies editors- giving the application consumer the freedom to chose admin widgets without modifying original app source. Author ====== [David Davis](http://www.davisd.com) (http://www.davisd.com) [dynamically change django admin widets at runtime (django-adminwidgetswap) blog post](http://www.davisd.com/blog/2010/04/17/dynamically-change-django-admin-widgets-at-runtime/) Usage =============== To change a widget in django's admin, just put adminwidgetswap.py on the python path, import adminwidgetswap.py and use: adminwidgetswap.swap_model_field(model, field, widget) ...to change a widget for a direct model admin's field --- adminwidgetswap.swap_model_inline_field(model, field, widget) ...to change widgets for inlines of a specific model and field --- adminwidgetswap.swap_model_and_inline_fields(model, field, widget) ...to change both the widget for the direct model admin's field as well as all inline usages for the model and field --- I usually have a project-level application called website, and I put this initialization code inside the website app's __init__.py Usage - parameters =============== model is the Model class (eg. models.GalleryImage) field is the field name you're looking to swap (eg. 'image') widget is the widget you're going to swap for (eg. widgetlibrary.ThumbnailWidget())

  • admin
  • widgets
  • abstraction
Read More

Partial templates, combine with and include

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 your regular template folders. The variables are passed in a with compatiable syntax, eg. VAR as NAME and VAR as NAME No limitations on the number of variables passed.

  • template
  • templates
  • partial
  • with
  • include
  • partials
Read More

immitating 'real' post_syncdb signal

I did not like the idea of having to load fixtures by creating a huge initial_data.json file. I also did not want to store my initial data in a bunch of <modelname>.sql files. Django has post_syncdb signal which fires when model(s) for an application are installed, but I needed something that would run only *once* at the end of syncdb command, at least after all of the models are installed, and here's what I've come up with. The code basically checks if the current callback is for the last app in your INSTALLED_APPS, and if so, executes some fixture loading code.

  • signals
  • post_syncdb
Read More

Excel Date

This allows you to just call excel_date and it will convert any dates between excel and python datetime.

  • date
  • excel
Read More

Custom Template Tag - No Translate

Forces Django not to translate built in template tags and filters. If you have a multi-lingual site but certain parts of it are not all translated, you can use this snippet to force Django to bypass translation on all template tags and filters so things like dates aren't randomly translated whilst everything else is not. For example: `{% notrans %}{{download.doc|filesizeformat}}{% endnotrans %}` This snippet including the filesizeformat template tag would not be translated. Mega thanks goes out to Dan Fairs for all his help on this!

  • translation
  • multi-lingual
  • custom-template-tags
Read More

Wrapper-function Pattern

This is an example how to create a wrapping function that can read all incoming arguments, do something with them and then call the original function. This pattern works well with generic views. Note that wrapper function accepts arguments in both ways: as a list of unnamed arguments and as a list of keyword-value pairs. A real-world example: def published_object_list(request, *args, **kwargs): arg_names = object_list.func_code.co_varnames params = dict(zip(arg_names, args)) params.update(kwargs) params['queryset'] = params['queryset'].filter(is_published=True) if request.is_ajax(): params['template_name'] = "ajax/" + params['template_name'] return object_list(request, **params)

  • view
  • function
  • wrapper
Read More

Add httponly to session cookie

Middleware to set "sessionid" (ou your session cookie) with httponly (see ["Django bug report"](http://code.djangoproject.com/ticket/3304)). To work, you need put it before "SessionMiddleware"

  • cookie
  • security
  • httponly
Read More

plaintext filter

Inspired by this [terse blog post](http://www.ghastlyfop.com/blog/2008/12/strip-html-tags-from-string-python.html). This filter was designed to simplify the stripping out of all (x)html in a given template var, while preserving some meta information from anchor, and image tags. Why is this even useful? If you have pre-assembled portions of templates, or model fields containing html, that you want to use to populate a *search index* like [django-haystack](http://haystacksearch.org/) you can safely discard all the markup, while keeping the text that should be still searchable. Alt text, and title attributes are worth keeping!

  • template
  • filter
  • striptags
Read More

Custom model field to store dict object in database

**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/).

  • models
  • fields
  • json
Read More

Dictionary of choices based in models

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.

  • forms
  • choicefield
  • zip
  • list-of-tuples
  • orm-and-forms
Read More

3109 snippets posted so far.