Login

Top-rated snippets

Snippet List

CountryField

**How to use** put this code somewhere you want, import CountryField and use

  • field
  • country
  • countries
Read More

AutoSlugField

This is a simple solution aimed at saving some time when you simply want to get a slug from a model field just before saving.

  • fields
  • slug
  • field
Read More

Another means of updating a subset of a model's fields

Based on the UPDATE query section of `Model.save()`, this is another means of limiting the fields which are used in an UPDATE statement and bypassing the check for object existence which is made when you use `Model.save()`. Just make whatever changes you want to your model instance and call `update`, passing your instance and the names of any fields to be updated. Usage example: import datetime from forum.models import Topic from forum.utils.models import update topic = Topic.objects.get(pk=1) topic.post_count += 1 topic.last_post_at = datetime.datetime.now() update(topic, 'post_count', 'last_post_at') (Originally intended as a comment on [Snippet 479](/snippets/479/), but comments aren't working for me)

  • model
  • db
  • update
Read More

Select multiple using a manytomany checkbox

Usage: from yourapp.fields import CheckBoxManyToMany from django.db import models class Weekday(models.Model): name = models.CharField() def __unicode__(self): return self.name class EventWithWeekday(models.Model): weekdays = CheckBoxManyToMany(Weekday)

  • checkbox
  • multiple
  • oldforms
  • select
Read More

FileField / ImageField with a delete checkbox

Example model: class MyModel(models.Model): file = RemovableFileField(upload_to='files', \ null=True, blank=True) image = RemovableImageField(upload_to='images', \ null=True, blank=True) A delete checkbox will be automatically rendered when editing such a model using form_for_instance. [UPDATED version which works with ModelForms](http://www.djangosnippets.org/snippets/636/)

  • newforms
  • models
  • imagefield
  • filefield
  • remove
  • delete
Read More

HTML to POST dict converter

If you want to test a post request to a form, you need to give all input fields, even if you just want to test if one value gets changed. This snippets parses the HTML of a view and gives you a dictionary that you can give to django.test.Client.

  • testing
Read More

Template filters utils

**Explanation:** That template filters is util for combine boolean-return conditions using template tag `{% if %}`. **Setup:** Insert the snippet into an_app/templatetags/myutils.py. **Use in template:** {% load myutils %} and use filters as following: - `{% if 10|is_multiple_of:5 %}` - `{% if 10|in_list:a_list_variable %}` - `{% if user.username|is_equal:a_variable %}` - `{% if user.username|is_not_equal:a_variable %}` - `{% if a_variable_|is_lt:5 %}` - `{% if a_variable_|is_lte:5 %}` - `{% if a_variable_|is_gt:5 %}` - `{% if a_variable_|is_gte:5 %}`

  • template-filters
Read More

Mako support as decorator

This snippet allows you to use @mako("templatename.mako") to define a mako template to use. Your python method just has to return a dictionary that will be passed to mako's context, after the addition of the "request" variable to the dictionary. If you return a non-False non dictionary object, it will return that instead of trying to render the template. The **request** variable is automatically added to the template's context. It also searches the current application's mako_templates/ subdirectory first before searching under the current directories mako_templates/, and does not use other application's mako_templates/ subdirectories at all. On Mako exceptions, it will display the Mako error page when debugging is enabled (hoping for extensible exception handling in the future to keep consistency) I got the idea from a [CherryPy tool](http://tools.cherrypy.org/wiki/Mako).

  • mako
Read More
Author: rmt
  • 2
  • 2

Copy/Paste form generation

Generator to help make newforms classes a bit like inspectdb does for generating rough model code. This is a standalone script to go in your project directory with settings.py and called from the prompt. It looks up the model, and generates code to copy/paste into your app. Hopefully to make a building a custom form with a lot of fields a little easier. Every argument should be a model identifier of form appname.modelname. Usage from the command line: python form_gen myapp.MyModel myapp.MyOtherModel

  • form
  • copy
  • generator
  • paste
Read More

ingore_fields

I use this snippet when creating newforms with form_for_model and form_for_instance. Both do not have an argument that lets you filter out fields easily so I wrote this instead. Typical use: `form_class = form_for_instance(obj, fields=ignore_fields(model_class, ['field_name1']))`

  • newforms
  • fields
  • ignore
Read More

Handling choices the right way

This solves the problem with **choices** described [here](http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/) Define your choices like this (in models.py): statuses = MyChoices(BIDDING_STARTED=10, BIDDING_ENDED=20) And then: status = models.IntegerField( default=statuses.BIDDING_STARTED, choices=statuses.get_choices() )

  • models
  • admin
  • choices
Read More

Per-site vary cache on language

I like the per-site caching offered by Django (it's simple) and I like the cache to be dependent on the chosen language. Unfortunately with the current `CacheMiddleware` you can either have the one or the other but not both at the same time. `VaryOnLangCacheMiddleware` is a small wrapper around `CacheMiddleware`. It looks at the `request.LANGUAGE_CODE` (set by `LocaleMiddleware`) and appends it to your `CACHE_MIDDLEWARE_KEY_PREFIX`. So "mysiteprefix" becomes "mysiteprefix_en" or "mysiteprefix_de-AT" depending on the user's chosen language. Site-wide, so no messing with per-view decorators and stuff. To use this, make sure `VaryOnLangCacheMiddleware` comes below `LocaleMiddleware` in your settings.py. If you haven't set your `CACHE_MIDDLEWARE_KEY_PREFIX`, it's works, too. **Update:** Replaced `super()` calls with `CacheMiddleware.xxx(self, ...)`.

  • middleware
  • i18n
  • cache
  • language
Read More

Dynamic Models Revisited

Somebody mentioned in #django the other day that they have multiple databases with the same schema... Well *lucky me* so do I!! This is one way to work with this issue. I've also included migrate_table_structure just in case the schema doesn't exist in the new database yet. As per the multiple-db-support branch, write all of your databases into the OTHER_DATABASES in settings.py. You can now copy models from your various models.py files and use them in different databases at the same time. This can also be used to migrate databases from one dialect to the other without having to translate your data into an interim format (e.g. csv, XML). You can just do: qs = MyModel.objects.filter(**filters) NewModel = duplicate_model_and_rels(MyModel, 'new_db') #Assuming that the schema is already in new_db: for mod in qs: new = NewModel() new.__dict__ = mod.__dict__ new.save() I tried this using some hacks with SQLAlchemy, and the above approach is a huge amount quicker! I've used this to copy some stuff from an oracle db, into a sqlite db so i could carry on working later and transferred about 20,000 in 5 mins or so. GOTCHAS ======== This only works against my copy of multi-db as I've made a couple of changes. My copy is substantially the same as my patch attached to ticket 4747 though, so it might work to a point (especially the data migration aspect). If it doesn't work hit me up and I'll send you my patch against trunk. I'm not too crazy about the code in copy_field, it works fine, but looks ugly... If anyone knows of a better way to achieve the same, please let me know.

  • dynamic
  • multi-db
  • copy
Read More
Author: Ben
  • 2
  • 7

3110 snippets posted so far.