Login

All snippets written in Python

Snippet List

Alias Field

A "fake" model field which is an alias to another underlying database field. Mirrors everything including queryset lookups, instance attributes, even if the field has been used on the model already (this isn't possible just by using db_column).

Read More
Author: s29
  • 0
  • 0

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

geodjango Metric Buffer

GEOSGeometry.buffer() accepts a distance argument which is in the unit of the coordinate reference system of the geometry. It is often necessary, however, to specify the buffer size in a more down-to-earth coordinate system, for example meters. with_metric_buffer(geom, buf_size) implements this functionality.

Read More

decorator for runsnake

1. Add this decorator to whatever function: @profile('/tmp/0123test.prof') def test_function(): pass 2. If it's a django view function, let it run once. 3. Use "runsnake" to open the ".prof" file. Sweet.

Read More

Previewing Django templates in a browser, without even creating a Django project

**preview_template.py** allows you to test a Django template located in the current working directory (first argument). The template is rendered with the given context (second argument, *optional*), and the result is immediately piped into the browser with the [bcat](http://rtomayko.github.io/bcat/) utility. **Usage:** python preview_template.py [template name] [context] **Example:** python preview_template.py template.html "{'username': 'Његош'}"

Read More

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

2955 snippets posted so far.