Login

All snippets

Snippet List

Template filter for internal links in TextFields

Allows for in internal link markup to be saved inside markdown-formatted Textfield entries. Using the filter, the link is only looked up at display time, so if your view's URL has changed, that should automatically update with the reverse() lookup. You could tweak the regex pattern to match whatever link markup you prefer. I also use Markdown to process my description fields, so I make the link return a markdown-formatted link instead of HTML, but you could tweak that too. If you use Markdown, you'd want to put this filter first. So to display a description TextField with internal links, in the template would be something like this: `{{ entity.description|internal_links|markdown }}` (See the [Django docs on writing your own custom filters](https://docs.djangoproject.com/en/1.6/howto/custom-template-tags/#writing-custom-template-filters) for more details on writing and registering filters.) Written for [my own website](http://opticalpodcast.com), and a basic version was shared as the [answer to this Stack Overflow question](http://stackoverflow.com/a/26812762/429070).

Read More

Forcing DB on relationship manager with multiple database project

I have a master/slave SQL setup and sometimes I need to access the data immediately after write, but the data has not yet propagated to the slave yet. This forces me to require `.using('default')` every time that relationship is accessed. Ex: self.books.using('default').all().delete() Setting `objects = ForceDefaultDBManager()` on the related object removes this requirement throughout your code. This now does the same as the last example: self.books.all().delete()

Read More

Extended Seconds-to-Duration Template Tag

Extended Template Tag initially created by Dan Ward (http://d-w.me): https://djangosnippets.org/snippets/1398/ The default setting has been renamed to normal, output stays the same. If you have used the old tag with ':short' you have to remove or rename it to ':normal' for the same ouput! As an example, given the duration 84658: Short: 23:30:58 Normal (default): 23 hrs 30 mins 58 secs Long: 23 hours, 30 minutes and 58 seconds Best regards, Gregor Volkmann

Read More

log django exceptions to file

Log Django exceptions to file. Contains snippet for both WatchedFileHandler and RotatingFileHandler handlers. Configurations mentioned are separate And only works if the DEBUG = False. Use "python manage.py runserver --no-reload" If you get file in use error.

Read More

Localized Shell

For historical reasons, Django commands are hard-coded to use `en-us` regardless of language. This includes the `shell` command and can lead to surprising effects if one assumes the local language to be the one set by `LANGUAGE_CODE`. This snippets can be saved as a management command in any app, for example using the name `lshell` and provides a localized shell controlled by the normal `LANGUAGE_CODE` setting.

Read More

Search child models in django admin changelist

If you use django admin interface and have added an admin page for a model, django gives out-of-box search functionality in the model fields or foreignkey fields. One thing it doesn't support is searching in child models. For example you have created an admin page for Student model and there is model for courses which stores one or more courses taken by students and if you want to search by course name on the student page to see which students took a particular course. Django doesn't let you do that. I have written a small utility which will let you do that. Just copy the snippet in a file and then inherit from the ChildSearchAdmin instead of ModelAdmin and then you can specify which model/fields you want it to search on. The syntax is: **child_searches = [(ChildModel, 'field_to_search_on', 'foreign_key_field_in_child_model'),..] Example: class StudentAdmin(ChildSearchAdmin): child_searches = [(StudentCourse, 'course', 'student')]

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

Another Multiform

MultiForm and MultiModelForm Based on a PrefixDict class I wrote and thus very lean. Lacks a little documentation, though class MyMultiForm(ModelMultiForm): class Meta: localized_fields = '__all__' form_classes = OrderedDict(( ('form1', Form1), ('form2', Form2), )) Subfields are named `form-name` `prefix_sep` `subfield-name`. `prefix_sep` defaults to `-`. For access in templates, use `form.varfields`, which uses `var_prefix_sep` (default: `_`), instead. multiform.varfields()['form1_field1']

  • models
  • forms
  • multiform
Read More

3109 snippets posted so far.