Login

Top-rated snippets

Snippet List

RecaptchaForm

There already is a [snippet on here](http://www.djangosnippets.org/snippets/433/) that shows how to use reCAPTCHA with Django, but being the lazya-- that I am, I wanted the form to: * display the captcha when as_table is used * handle captcha validation for me So RecaptchaForm does the trick. Just subclass from it and voila, your form will include reCAPTCHA validation. Other than that, you need to * be on Django trunk version (or use clean_data instead of cleaned_data for 0.96) * set RECAPTCHA_PRIVATE_KEY and RECAPTCHA_PUBLIC_KEY in your settings.py * make sure that the [captcha module](http://pypi.python.org/pypi/recaptcha-client) is available somewhere (i.e. that "import captcha" works)

  • captcha
  • recaptcha
Read More

JSON encoding middleware

Makes it really easy to return JSON from your views: just return a dict. (Also from [django-webapp](http://code.google.com/p/django-webapp/).)

  • middleware
  • serialize
  • json
  • encode
  • encoding
  • serializer
Read More

Ajax error handling

Handles exceptions from AJAX code, giving more useful errors and tracebacks. (By the way, all these new snippets are extracts from [django-webapp](http://code.google.com/p/django-webapp/).) This exact code is not well tested, but it's refactored from some code we use in production.

  • middleware
  • ajax
  • error
  • exception
Read More

Default settings for a app

Save this as conf.py in the app's directory. Now you can do `from myapp.conf import settings`. You can access from the imported object every item of your settings.py including the default settings of myapp. Though you don't have to define every setting in settings.py you use in your app. Now you can ommit annoying try...except statements to define defaults directly in the code.

  • settings
  • conf
  • app
Read More

CSVImport

This is an awesome script! The original can be found here: http://www.djangosnippets.org/snippets/633/ I had to make a couple minor changes to get it working for me, so I thought I would share the love...

  • csv
  • import
Read More

Javascript Chain Select Widget

This widget will render a chained select menu powered by JavaScript to make it easier to identify foreign keys. This widget includes danjak's form decorator (http://www.djangosnippets.org/snippets/59/), and Xin Yang's chained select javascript functions (http://www.yxscripts.com/). I developed this to be used with an IT inventory system. See screenshot here: http://bayimg.com/cAjAGAabN The models are laid out that location -> area -> room. But the __str__ of area and room did not include unique fields, so the built-in single select box that django uses for ForeignKey's did not work for me. A few notes: 1: I will not be maintaining this, I am only putting it out here in case it helps others. 2: The chained select menus will only be available to the first form on the page. Reason being: the template names the form, not the django backend. So, I had to reference the form in javascript as document.forms[0]. 3: Due to the javascript processing, the chain select menu will not show current values other than the default specified in the javascript. Thus, form_for_instance and a dict of values passed to form_for_model will not pre-set the chained select. 4: The rendered selects are put into a vertical table. No other layout is supported. 5: The select field names for upper-leveled options are "chain_to_[destination_field_name]__[current_selects_model_name]. 6: The select name for the destination option is the name that django sends internally, which is usually the field name. The value of each option in the select is the primary key associated with that object. 7: I tried to get this built in to the native form_for_model helper function for use with the default admin site, but failed miserably. How to get it working (quick version): 1: Define your models 2: From your view, import the form_decorator and ChainSelectWidget (I put them in CustomWidgets.py and made sure it was in the path). 3: Build arguments for the form_decorator eg: widget_overwrite=dict(field=ChainSelectWidget(order=[(top, 'order_field'), (next, 'order_field'), (field, 'order_field)] 4: Send arguments to form_decorator eg: callback = form_decorator(widgets=widget_overwrite) 5: Build modified form eg: mod_formclass = form_for_model(field, formfield_callback=callback) 6: Instance the modified form eg: instanced_form = mod_formclass() 7: Send instanced form to the templating engine 8: From the template, import the chainedselects function file (replace [] with <>) eg: [head][script language="javascript" src="path/to/chainedselects.js"][/script] 9: Display the form object as you normally would.

  • javascript
  • dynamic
  • widgets
  • select
  • widget
  • js
  • java
  • chain
Read More
Author: ogo
  • 1
  • 7

Template range tag

This is a simple tag that I am sure has been written before, but it helps people with the problem, 'how do I iterate through a number in the tempaltes?'. Takes a number and iterates and returns a range (list) that can be iterated through in templates Syntax: {% num_range 5 as some_range %} {% for i in some_range %} {{ i }}: Something I want to repeat\n {% endfor %} Produces: 0: Something I want to repeat 1: Something I want to repeat 2: Something I want to repeat 3: Something I want to repeat 4: Something I want to repeat

  • template
  • context
  • range
Read More

MySQL "Text" Type Model Field

Custom field for using MySQL's `text` type. `text` is more compact than the `longtext` field that Django assigns for `models.TextField` (2^16 vs. 2^32, respectively)

  • text
  • models
  • mysql
  • db
  • database
  • field
  • custom-field
Read More

YAAS (Yet Another Auto Slug)

This is the self-populating AutoSlugField I use. It's not the [first such snippet](http://www.djangosnippets.org/tags/slug/), but (IMO) it works a bit more cleanly. It numbers duplicate slugs (to avoid IntegrityErrors on a unique slug field) using an "ask-forgiveness-not-permission" model, which avoids extra queries at each save. And it's simply a custom field, which means adding it to a model is one line. Usage: class MyModel(models.Model): name = models.CharField(max_length=50) slug = AutoSlugField(populate_from='name')

  • slug
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

Google Map Field and Widget

There is a sample in the code. You can use this snippet to allow your forms to easily edit object locations. Take care about what you should add to your templates in order to make it work.

  • newforms
  • field
  • widget
  • gmap
  • map
  • google-map
Read More

Admin change language

This snippet adds a select language drop down menu in the admin bar (just after Documentation link). For this approach it's necessary to copy from admin templates the admin/base.html to the project templates (keeping the admin directory), changing just line 25 ad shown. Then it's necessary to create specified admin/change_language.html template.

  • admin
  • language
  • change
Read More

AlphabeticFilterSpec

**WARNING: a better version of this snippet you can see at [http://www.djangosnippets.org/snippets/1051/](http://www.djangosnippets.org/snippets/1051/)** This filter spec is util only for who uses newforms-admin branch. To use this, you need to extend the class ModelAdmin for your model class, like the MyClassAdmin class in the code, with attention to the following lines: # Appends the filter cl.filter_specs.insert(0, AlphabeticFilterSpec(cl.lookup_opts.get_field('name'),request,cl.params,self.model,self))

  • filter
  • admin
  • alphabetic
Read More

3110 snippets posted so far.