Login

Top-rated snippets

Snippet List

Readonly Select Widget Replacement

This is for situations where a ModelForm is needed on an existing object, but we want to disable ForeignKey widgets, and only use them as a display. Usage: save the code in the top half of the example above into a file somewhere in your django project, in this example we will call it customwidget.py The second half shows an example usage, but setting the widget and queryset in the __init__ method of the form. If the queryset returned by the ForeignKey model (Example.objects.all() ) is small, you can omit the __init__ code.

Read More

Multiple Model Forms feeding a single Form to use with a single FormView

This is a simple example of feeding multiple Forms into a single Form via its constructor method, to work with a single FormView and reap the benefits of Django's awesome Form validation system. It's a Form class that defines (or takes via an argument to its constructor) *parent* Forms (that can, for instance, be ModelForms, to take advantage of the automatic Field generation) and takes its fields from there. An advanced user won't be impressed by this, so excuse if this snippet is out of place, but a rather inexperienced user such as myself might find it interesting and make him willing to explore Django's internals a bit more.

Read More

Export queryset to Excel workbook

How to use =========== Save the snippet to a file utils.py, and add the following view to your Django app: from django.http import HttpResponse from .utils import queryset_to_workbook def download_workbook(request): queryset = User.objects.all() columns = ( 'first_name', 'last_name', 'email', 'is_staff', 'groups') workbook = queryset_to_workbook(queryset, columns) response = HttpResponse(mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="export.xls"' workbook.save(response) return response Note: you can use dotted notation (`'foreign_key.foreign_key.field'`) in the columns parameter to access fields that are accessible through the objects returned by the queryset (in that case you probably want to use `select_related` with your queryset).

  • export
  • queryset
  • xlwt
Read More

Encrypted Custom Model Field

Custom model field to support two ways encryption. The key is provided in the app settings.py file. It should be at least 32 chars. ** usage ** Assuming that you placed the new code into fields.py from app.fields import EncyptedField class Account(models.Model): password = EncryptedField()

  • custom-model-field
  • encrypted
Read More

Virtualfish Hook

When you use Virtualfish, the virtualenv wrapper for the fish shell, you can add hooks for whenever the virtualenv is activated. This little snippet sets some important environment variables and adds the manage.py command with autocompletion so that you won't ever need to write "python ./manage.py help" ever again, but only "manage <TAB>". For this to work you need to source or paste this code in your ~/.config/fish/config.fish

  • manage
  • virtualenv
  • fish
  • virtualenvwrapper
  • virtualfish
Read More

Pretty Print Template Tag

This defines a new template tag that lets you print your rendered templates (or partial templates) in html that has been prettified by beautiful soup. It is dependent on the beautiful soup library (bs4). Not recommended for production but it is helpful for development and serving readable html. {% load whatever_template_file %}' <body> {% pretty %} <h1>Hello, world.</h1> {% endpretty %} </body>

  • beautiful-soup
  • template-tag
  • pretty-print
Read More

Dynamic SITE_ID thread-safe

Store in SiteID a local var store for save SITE_ID thread-safe and set it with middleware. It's base on https://djangosnippets.org/snippets/1099/ but with call to local() in SiteID and using custom models for web site and domains.

  • dynamic
  • site_id
  • thread-locals
Read More
Author: jhg
  • 1
  • 0

Read-only Model Form Base Class

The simplest way of displaying a "details" table about any model, is to show a ModelFrom with all fields readonly or (selects) disabled. Also, the labels are preferably translatable, not just capitalized names of the column tables in your models. So the constructor translates the field labels as well.

  • form
  • readonly
Read More

Django Settings Splitter & Local Settings loader

Everybody know about long spagetty-style settings file for django :-) I tried to find any cool settings loader, but have no luck.I created this one myself. Ok, we forgetting about `settings.py` and creating module settings (folder named settings with file `__init__.py`). This `__init__.py` file have preloader for modules placed in settings folder and `../settings_local.py` (if exists) at the end. settings_local is awesome tool, when you use any VCS like git and have settings in vcs, but for example you have different database connection settings. You can change this settings in settings_local. Settings splitter have variable moduleweights. This variable declares weights for selected modules to allow loader sort modules by priority and use already defined settings in each other loaded module. You can define your custom modules and weights there. Ok, now few examples. settings/env.py import os # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ DEBUG = not 'http/ask.helldude.ru/' in os.path.realpath(__file__) settings/assets.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ import os import sys settings = sys.modules['project.settings'] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(settings.BASE_DIR, 'static') STATICFILES_DIRS = (os.path.join(settings.BASE_DIR, "project/static"),) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) settings_local.py: import sys settings = sys.modules['project.settings'] print 'I WAS LOADED KHA KHA KHA' if settings.DEBUG: print 'In debug mode' You can see amazing 'hack' there :-) I use already defined settings via sys.modules['project.settings'] (where project is common folder for my project applications). I hope you like this small lifehack for django settings! rudude.

  • django
  • settings
  • local
Read More

Group permissions selection in admin filtered by your app models

Sometimes you just don't want to display every permission django has, you just want a short list showing the permissions for some of your apps (or even django core apps). GROUP_PERMISSIONS_MODELS must be a list of your app models. Dotted path (in lowercase) required, app name + model *class* name.

  • admin
  • group
  • permissions
Read More

ModelChoiceField with choice groups for recursive relationships

Note: must call within __init__() method, so you must do self.fields["field"] = ModelChoiseField(...). This is because I did not use a ModelChoiceIterator. A subclass of ModelChoiceField which represents the tree level of each node when generating option labels. It's limited to one level of nesting, if you need more, you should consider the django-mptt package. For example, where a form which used a ModelChoiceField: category = ModelChoiceField(queryset=Category.objects.all()) ...would result in a select with the following options: --------- Root 1 Root 2 Child 1.1 Child 1.2 Child 2.1 Using a NestedModelChoiceField instead: category = NestedModelChoiceField(queryset=Category.objects.all(), related_name='category_set', parent_field='parent_id', label_field='title') ...would result in a select with the following options: Root 1 --- Child 1.1 --- Child 1.2 Root 2 --- Child 2.1

  • ModelChoiceField
Read More

ContentType template filter

Custom template filter to retrieve a content type of a given model instance. Useful for ModelForms which want to set the content_type field (i.e: GenericForeignKey). ### A usage example: {% load helpers %} {% with instance|content_type as ctype %} <input type="hidden" name="content_type" value="{{ ctype.pk }}"> {% endwith %} Original idea from [this stackoverflow answer] [1] [1]: http://stackoverflow.com/a/12807458/484127

  • template
  • filter
  • tag
  • contenttypes
  • contenttype
  • GenericForeignKey
Read More

Multiple emails form field

Validate form field that include email or emails separated by 'token' kwargs, by default ',' a comma. Return a list [] of email(s). Check validity of the email(s) from django EmailField regex (tested with 1.3, but normally will also work with 1.5)

  • multiple
  • email
  • validation
  • form
  • field
  • list
Read More

View all log entries in the admin 2

Based on: [View all log entries in the admin](https://djangosnippets.org/snippets/2484/) Improvements: * No crash on `object_link` when reverse route missing, * Filter by users present in the log AND in database currently * Other filters on users - only superusers / only staff (modify to fit your needs) EDIT: Incorporated `action_description` from [django-logentry-admin](https://github.com/yprez/django-logentry-admin). * The list filter now has human-friendly action names, and the table also. * Refactored list filter class hierarchy.

  • admin
  • list-filter
  • logentry
Read More

3110 snippets posted so far.