Login

Snippets by Archatas

Snippet List

Detailed Error Reporting by Email

The default traceback sent by email when an error occurs, usually gives too little information comparing it to the error page in the DEBUG mode. This snippet guerilla-patches error handling and sends by email the same information as you would see in DEBUG mode. To set it up, add the snippet to any `models.py` of an installed app. (I wonder why this hasn't been implemented in the core)

  • email
  • error
  • reporting
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

Conditional Caching

This trick is for caching a view only if it passes some condition, for example, if there are more than zero items in a list. The same methodology could be used for conditional applying of other decorators.

  • views
  • cache
  • decorators
Read More

Dynamic import from an installed app

This is an example how to dynamically import modules other than `models.py` from installed apps. It allows you to define the full module path just once in `INSTALLED_APPS` in the settings. Using this technique makes it possible to write extensible and reusable apps as mentioned in [Abstract Models and Dynamicly Assigned Foreign Keys](http://djangotricks.blogspot.com/2009/02/abstract-models-and-dynamicly-assigned.html). Probably, it would be great to have some helpers for doing this in django itself. For example: from django.db import models from django.utils import importlib def import_installed(path): """ Imports a module from an installed app >>> import_installed("myapp.forms") <module 'myproject.apps.myapp.forms'> """ app_name, module = path.split(".", 1) app = models.get_app(app_name) return importlib.import_module(app.__name__[:-6] + module) UPDATE: Reported as ticket [#10703](http://code.djangoproject.com/ticket/10703)

  • dynamic
  • import
Read More

Alternative to Captchas (Without Human Interaction)

This security field is based on the perception that spambots post data to forms in very short or very long regular intervals of time, where it takes reasonable time to fill in a form and to submit it for human beings. Instead of captcha images or Ajax-based security interaction, the SecurityField checks the time of rendering the form, and the time when it was submitted. If the interval is within the specific range (for example, from 5 seconds till 1 hour), then the submitter is considered as a human being. Otherwise the form doesn't validate. Usage example: class TestForm(forms.Form): prevent_spam = SecurityField() # ... other fields ... The concept works only for unbounded forms.

  • captcha
  • security
  • form
  • field
  • antispam
  • antibot
Read More

Multiple-Submit-Button Widget for Choice Field

Django administration provides three buttons for submitting the currently edited object. Each of them has a unique name and depending on the name that is sent to the server, the specific action is performed. I see this as an ugly solution and prefer to have a choice field in the form which would render as submit buttons with different values. Then the values would be checked instead of the names. Therefore, I created the `MultipleSubmitButton` widget. When `<input type="submit" value="Go" />` is used, the value sent to the server always matches the text on the button, but if `<button type="submit" value="go">Go</button>`, the value and the human representation might differ. To use the `MultipleSubmitButton` widget, pass it to the widget parameter of a `ChoiceField` like this: SUBMIT_CHOICES = ( ('save', _("Save")), ('save-add', _("Save and Add Another")), ) class TestForm(forms.Form): do = forms.ChoiceField( widget=MultipleSubmitButton, choices=SUBMIT_CHOICES, ) When you print `{{ form.do }}` in the template, the following HTML will be rendered: <ul> <li><button type="submit" name="do" value="save">Save</button></li> <li><button type="submit" name="do" value="save-add">Save and Add Another</button></li> </ul> When you submit this form and check the validity of it, `form.cleaned_data['do']` will return "save" or "save-add" depending on the submit button clicked.

  • forms
  • widget
  • submit
Read More

Setting distinction between development and public server

If your code is under source control and you develop locally and then publish that globally, you might need to modify the settings file after each update to ensure the system paths and database settings are correct. This simple solution helps to distinguish development server from the public server. And you won't need to care about modifying files on the public server anymore. Create a file called `dev_environment.py` in your `site-packages` directory of the development server only (do not put it under source control). Then use the following lines in the beginning of your files, you want to check whether you are in the development environment. try: from dev_environment import * except: is_dev_environment = False Then for example, you can set the database settings according the environment: if is_dev_environment: DATABASE_NAME = "test" DATABASE_USER = "root" DATABASE_PASSWORD = "" else: DATABASE_NAME = "publicproject" DATABASE_USER = "projectuser" DATABASE_PASSWORD = "ahl3379ljkasd"

  • development
  • public
Read More

Multilingual Models

A way to implement models with translatable content. The translatable field of the default language has no extension, like "title" and the translations have extensions postfixes "_<two-letter language code>", like "title_la" or "title_mn". Method get_title() in this case returns the translation of the currently chosen language or the title of the default language, if the translation is not set. The class XFieldList overrides the default list class and is used for modifying ordering and list_display settings according the chosen language. For example, when the German language is chosen, the list of translatable content objects will be ordered by German titles (not English). *At the time when the list of field names is assigned to ordering or list_display (at the import of the model), the currently chosen language is still not known. But the language is known when ordering and list_display lists are used in contributed administration or elsewhere.* The XFieldList returns the modified values of the passed-in list, when its methods/properties are triggered. XFieldList transforms field names ending "_" (except the ones beginning with "__", like "__str__") to appropriate translations according the currently chosen language. For example ['title_', 'content_', 'is_published'] will be changed to ['title', 'content', 'is_published'] for the English language and to ['title_lt', 'content_lt', 'is_published'] for the Lithuanian language. *The best practice is to put XFieldList into a separate file and import it from different apps whenever needed.* It's worth mentioning that one implementing this should also know about [Django internationalization](http://www.djangoproject.com/documentation/i18n/).

  • i18n
  • l10n
  • translations
  • multilingual
Read More

Archatas has posted 8 snippets.