Login

All snippets

Snippet List

make an unordered html list

This custom filter takes in a string and breaks it down by newline then makes each separate line an item in an unordered list. Note that it does not add the <ul> </ul> tags to give the user a chance to add attributes to the list. This is based of the 'linebreaks' filter built in django

  • html
  • list
Read More

DebugFooter middleware

Adds a hidden footer to the bottom of every text/html page containing a list of SQL queries executed and templates that were loaded (including their full filesystem path to help debug complex template loading scenarios). To use, drop in to a file called 'debug_middleware.py' on your Python path and add 'debug_middleware.DebugFooter' to your MIDDLEWARE_CLASSES setting.

  • sql
  • middleware
  • debugging
Read More

EditInline for GenericForeignKey

A simple InlineModelAdmin class that enables you to edit models that are bound by the instance via a generic foreign key (`content_type`, `object_id` pair) Use like: class PlacementInlineOptions( generic.GenericTabularInline ): model = Placement extra = 2 ct_field_name = 'target_ct' id_field_name = 'target_id' Can be also found at #4667

  • admin
  • foreignkey
  • generic
  • edit-inline
Read More

Newforms Validation of Credit Card Numbers

Some functions and newforms fields for validating credit card numbers, and their expiry dates. In my project, I have all of the credit card functions in a file called creditcards.py Just as an overview: To validate a credit card number there are a few steps: 1. Make sure the number only contains digits and spaces. `ValidateCharacters()` 2. Remove spaces so that only numbers are left. `StripToNumbers()` 3. Check that the number validates using the Luhn Checksum `ValidateLuhnChecksum()` 4. Check to see whether the number is valid for the type of card that is selected. This is annoying because you will need to look at another cleaned field before you can check this.

  • newforms
  • field
  • credit-card
  • number
  • visa
  • mastercard
Read More

Truncate words by characters

This filter truncates words like the original truncate words Django filter, but instead of being based on the number of words, it's based on the number of characters. I found the need for this when building a website where i'd have to show labels on really small text boxes and truncating by words didn't always gave me the best results (and truncating by character is...well...not that elegant). Usage example: {{var|truncatewords_by_chars:"16 2 4"}} If string lenght is higher than 16, truncates by 2 words, if lesser, truncates by 4 words.

  • filter
  • truncate
  • character
  • word
Read More

pyserver -- runserver alias

I use Django's built-in development server all the time, but get tired of typing out the command to run it, and if I'm testing some custom admin css/js, I *really* get tired of typing out the command that correctly directs the middleware to use my admin media dir. So I added this alias to my .bashrc and when I'm in a project's root, I just type 'pyserver' and the development server fires up, automatically passing an --adminmedia arg if I have some custom admin media for the project (otherwise it's 'runserver' as always). Note: This relies on the convention that my custom admin media will be in a folder called admin_media that resides at the project's base. Of course, change it to whatever convention you use. I'm not a bash expert or anything, but this works for me ;)

  • bash
  • runserver
Read More

Automate unique slug (again)

This takes the "easier to ask forgiveness than permission" approach to making sure your model's slug is unique. If the model's slug is empty, make a slug from the model's 'name' field. We assume that it is a conflicting slug that is throwing the IntegrityError, in which case if the slug does not end with '-' followed by a number then append '-2'. If the slug does end with '-' followed by a number then capture that final number, increment it by one, save the new slug value and try savin g again.

  • slug
  • save
Read More

Callable Class View

Instead of using a function for your views, this allows you to use a class. For your urls definition it works just as it normally does.

  • view
  • callable
  • response
Read More

Reorder fields directly in the ModelForm

Sometimes the order of the fields you get from a model needs to be adjusted when displaying its modelform. If it's just a few fields you can do it in the template, but what if you want to iterate over the form? The fields are stored in a SortedDict, so you can change the order in the __init__ of the form. A bit clunky, yes.

  • newforms
  • modelform
  • field-order
  • workaround
Read More
Author: HM
  • 6
  • 5

DisplayModelForm

Subclass of the ModelForm which allows to make fields 'display_only'. This means no formfield will be displayed, but a suitable representation. You can make all fields display_only or just a few (or you can use the form as a normal modelform). There are also some extra's to easily set attrs on fields or set help_texts on widgets when using this form. Why ? I made my own set of generic crud views based on newforms, but added a 'display' view to simply display objects, in the same table layout as the editing is done, but without the fields. I wanted to avoid having to redefine my forms twice and I wanted to reuse some generic templates as much as possible. Obviously this is not good for performance, but I use it for an intranet app with a lot of objects, but not that big a load. Their is definitely still a lot of room for improvement, and maybe all this could have been done much easier. How to use? See the docstring.

  • modelform
Read More

module_from_path

I needed to dynamically import a module based on a path to that file on disk, without it necessarily being on the Python Path.

  • import
Read More

sort_by_id_sequence

I needed to sort a set of objects (a QuerySet for example) by an externally provided list of IDs - for example: >>> writers = Writer.objects.all() >>> sort_by_id_sequence(writers, [3, 1, 2]) [<Writer id: 3>, <Writer id: 1>, <Writer id: 2>]

  • sorting
Read More

Adding buttons to submit line in a Admin page

**Attention: this snippet depends on jQuery library to works** The Admin templates hierarchy does not allow you change the submit line (that buttons bar in the footer of the change view of a model class). This code shows how to resolve this, using a simple javascript trick. You can read the code and implement using your favorite javascript library (instead of jQuery) or pure JavaScript. This example regards to User Profile, a common used model class that adds custom fields to a user in the authentication system. To use this, you must put this template code in a file with the following name: templates/admin/auth/user/change_form.html

  • template
  • ajax
  • javascript
  • admin
  • query
Read More

decorator to add author to extra_fields in snippets 635

I had the need to add `request.user` to the `extra_fields` argument of quite a few of my view based on [create_update for newforms snippet](http://www.djangosnippets.org/snippets/635/). I could have wraped the `create_object` function in my views.py, but as the logic is always the same, it seemed like a good idea to Not Repeat Myself.

  • newforms
  • decorator
  • create_update
  • author
Read More

3109 snippets posted so far.