Login

Tag "models"

Snippet List

Autogenerate admin classes in admin.py

Tired of adding admin classes to admin.py whenever you add a model? This admin.py automatically keeps itself up-to-date with your models.py file. It assumes if you have a model: MyModel, you want an admin class called AdminMyModel. Regards, Luke Miller

  • django
  • models
  • admin
Read More

auto image field w/ prepopulate_from & default

Given such code: class ProductImage(models.Model): fullsize = models.ImageField(upload_to= "products/%Y/%m/%d/") display = AutoImageField(upload_to= "products/%Y/%m/%d/",prepopulate_from='fullsize', size=(300, 300)) thumbnail = AutoImageField(upload_to="products/%Y/%m/%d/",null=True,default='/media/noimage.jpg')) display will be automatically resized from fullsize, and thumbnail will default to /media/noimage.jpg if no image is uploaded Note: At some point the code broke against trunk, which has now been updated to work properly

  • image
  • models
  • db
  • field
Read More

Custom Django manager that excludes subclasses

When you're using Django model inheritance, sometimes you want to be able to get objects of the base class that aren't instances of any of the subclasses. You might expect the obvious way of doing this, `SuperModel.objects.filter(submodel__isnull=True)`, to work, but unfortunately it doesn't. (Neither does `SuperModel.objects.filter(submodel__supermodel_ptr=None)`, or any other convoluted way I could think of doing it.) Here's a nicer approach for doing this. [The blog entry is here.](http://sciyoshi.com/blog/2008/aug/07/custom-django-manager-excludes-subclasses/)

  • managers
  • models
  • model
  • subclass
  • manager
  • inheritance
  • subclasses
Read More

CustomImageField for Django 1.0 alpha

The venerable CustomImageField, invented by [Scott Barnham](http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/) and rejiggered for newforms-admin by [jamstooks](http://pandemoniumillusion.wordpress.com/2008/08/06/django-imagefield-and-filefield-dynamic-upload-path-in-newforms-admin/#comments). This here is a stab at a [post-Signals-refactor](http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Signalrefactoring) version. Seems to do 'er. Note: This should be pointless once [fs-refactor](http://code.djangoproject.com/ticket/5361) lands.

  • models
  • fields
  • imagefield
  • newforms-admin
  • signals
Read More

Models for Postal Addresses

Here's some fairly normalized models for representing postal addresses. Making postal_code a separate model would probably be the only way to get it to a level that everyone would agree is 2NF, but we handle a lot of international addresses so that isn't really feasible. Country and StateProvince are intended to be populated with data from ISO 3166. I'd include the SQL I used with that data, but it's very long and there's no attach feature. Also, I'd probably be violating ISO's copyright.

  • models
  • countries
Read More

Custom color field with Javascript color picker

A custom model field 'ColorField' which stores a hex color value like '#FFFFFF' and shows a Javascript color picker in the admin rather than a raw text field. It is written to work with the current trunk (i.e. after newforms-admin merge). You'll need the ColorPicker2.js file found at [www.mattkruse.com](http://www.mattkruse.com/javascript/colorpicker/combined_compact_source.html) (his license prohibits including the file here). This should be placed in the 'js' folder of your admin media. The snippet includes a python source file which can be placed wherever you wish, and a template which by default should be placed in a folder 'widget' somewhere on your template path. You can put it elsewhere, just update the path ColorWidget.render The custom field at present does not validate that the text is a valid hex color value, that'd be a nice addition.

  • newforms
  • javascript
  • models
  • admin
Read More

Translated choices fields

- Choices are saved as the key integers. - Admin will show the correct translation in forms. - You can reuse the make_choices function for other choices fields. - Bad side: bin/make_messages.py won't get the choices values automatically, you have to add them in the .po's by hand.

  • models
  • choices
  • i18n
Read More

PositionField

**This is a model field for managing user-specified positions.** Usage ===== Add a `PositionField` to your model; that's just about it. If you want to work with all instances of the model as a single collection, there's nothing else required. In order to create collections based on another field in the model (a `ForeignKey`, for example), set `unique_for_field` to the name of the field. It's probably also a good idea to wrap the `save` method of your model in a transaction since it will trigger another query to reorder the other members of the collection. Here's a simple example: from django.db import models, transaction from positions.fields import PositionField class List(models.Model): name = models.CharField(max_length=50) class Item(models.Model): list = models.ForeignKey(List, db_index=True) name = models.CharField(max_length=50) position = PositionField(unique_for_field='list') # not required, but probably a good idea save = transaction.commit_on_success(models.Model.save) Indices ------- In general, the value assigned to a `PositionField` will be handled like a list index, to include negative values. Setting the position to `-2` will cause the item to be moved to the second position from the end of the collection -- unless, of course, the collection has fewer than two elements. Behavior varies from standard list indices when values greater than or less than the maximum or minimum positions are used. In those cases, the value is handled as being the same as the maximum or minimum position, respectively. `None` is also a special case that will cause an item to be moved to the last position in its collection. Limitations =========== * Unique constraints can't be applied to `PositionField` because they break the ability to update other items in a collection all at once. This one was a bit painful, because setting the constraint is probably the right thing to do from a database consistency perspective, but the overhead in additional queries was too much to bear. * After a position has been updated, other members of the collection are updated using a single SQL `UPDATE` statement, this means the `save` method of the other instances won't be called. More === More information, including an example app and tests, is available on [Google Code](http://code.google.com/p/django-positions/).

  • lists
  • models
  • fields
  • model
  • field
  • list
  • sorting
  • ordering
  • collection
  • collections
Read More

CustomQueryManager

A `models.Manager` subclass that helps to remove some of the boilerplate involved in creating managers from certain queries. Usually, a manager would be created by doing this: class MyManager(models.Manager): def get_query_set(self): return super(MyManager, self).get_query_set().filter(query=blah) Other managers may return other query sets, but this is especially useful as one may define queries on a table which would be used a lot. Since the only part that ever changes is the `query=blah` set of keyword arguments, I decided to abstract that into a class which, besides taking the repetition out of manager definition, allows them to be and'd and or'd in a manner similar to the `Q` objects used for complex database queries. `CustomQueryManager` instances may be defined in one of two ways. The first, more laborious but reusable manner, is to subclass it, like so: class MyManager(CustomQueryManager): query = Q(some=query) Then, `MyManager` is instantiated with no arguments on a model, like normal managers. This allows a query to be reused without extra typing and copying, and keeps code DRY. Another way to do this is to pass a `Q` object to the `__init__` method of the `CustomQueryManager` class itself, on the model. This would be done like so: class MyModel(models.Model): field1 = models.CharField(maxlength=100) field2 = models.PositiveIntegerField() my_mgr = CustomQueryManager(Q(field1='Hello, World')) This should mainly be used when a query is only used once, on a particular model. Either way, the definition of `__and__` and `__or__` methods on the `CustomQueryManager` class allow the use of the `&` and `|` operators on instances of the manager and on queries. For example: class Booking(models.Model): start_date = models.DateField() end_date = models.DateField() public = models.BooleanField() confirmed = models.BooleanField() public_bookings = CustomQueryManager(Q(public=True)) private_bookings = public_bookings.not_() confirmed_bookings = CustomQueryManager(Q(confirmed=True)) public_confirmed = public_bookings & confirmed_bookings public_unconfirmed = public_bookings & confirmed_bookings.not_() public_or_confirmed = public_bookings | confirmed_bookings public_past = public_bookings & Q(end_date__lt=models.LazyDate()) public_present = public_bookings & Q(start_date__lte=models.LazyDate(), end_date__gte=models.LazyDate()) public_future = public_bookings & Q(start_date__gt=models.LazyDate()) As you can see, `CustomQueryManager` instances can be manipulated much like `Q` objects, including combination, via `&` (and) and `|` (or), with other managers (currently only other `CustomQueryManager` instances) and even `Q` objects. This makes it easy to define a set of prepared queries on the set of data represented by a model, and removes a lot of the boilerplate of usual manager definition.

  • models
  • q
  • manager
  • query
  • custom
Read More

i18n base model for translatable content

Together with my mentor, Dusty Phillips, I have developed a simple class that dynamically adds two fields to its subclasses. This is useful in cases when a single piece of content is divided into translatable and non-translatable fields, connected by a 1-to-many relationship. ## Update 2009/03/30 Since its inception, this snippet has grown into a significantly more powerful solution for translatable content (I use it myself with great joy :). The project is now hosted on github: [project page](http://github.com/foxbunny/django-i18n-model/tree/master) ## Update 2008/07/09 It is now possible to define `i18n_common_model` attribute in `class Meta` section. Here's an example: class Meta: i18n_common_model = "MyCommonModel" As you can see, it has to be a string, not the real class, and it is case-sensitive. ## Example class Article(models.Model): author = models.CharField(max_length = 40) class Admin: pass class ArticleI18N(I18NModel): title = models.CharField(max_length = 120) body = models.TextField() class Admin: pass # optionally, you can specify the base class # if it doesn't follow the naming convention: # # class Meta: # i18m_common_model = "Article" When the ArticleI18N class is created, it automatically gains two new fields. `lang` field is a CharField with choices limited to either `settings.LANGUAGES` or `django.conf.global_settings.LANGUAGES`. The other field is `i18n_common` field which is a ForeignKey to Article model. ## The conventions * call the translation model `SomeBaseModelI18N`, and the non-translation model SomeBaseModel (i.e., the translation model is called basename+"I18N") * the first convention can be overriden by specifying the base model name using the `i18n_common_model` attribute in `Meta` section of the `I18N` model * I18N model is a subclass of `I18NModel` class ## Original blog post [http://blog.papa-studio.com/2008/07/04/metaclasses-and-translations/](http://blog.papa-studio.com/2008/07/04/metaclasses-and-translations/)

  • models
  • i18n
  • metaclass
  • translated-content
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

dynamic model graph

This view assumes you have downloaded [modelviz.py](http://django-command-extensions.googlecode.com/svn/trunk/extensions/management/modelviz.py) and placed it in a python module called utils within my_project. You also must have graphviz installed and a subprocess-capable python. From there you can feed it a URL query list of the options you want to pass to generate_dot, and it will dynamically draw png or svg images of your model relationships right in the browser. All it wants is a nice form template for graphically selecting models. Most of this code and the main idea thereof was shamelessly plagiarized from [someone else](http://gundy.org/). Examples: `http://localhost:8000/model_graph/?image_type=svg&app_labels=my_app&include_models=Polls&include_models=Choices` `http://localhost:8000/model_graph/?image_type=png&all_applications&disable_fields&group_models`

  • models
  • graph
  • png
  • database
  • graphviz
  • modelviz
  • visualization
  • svg
Read More

Updated 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 using ModelForm or editing it using form_for_instance. Also, the filename or the image will be displayed below the form field. You can edit the render method of the DeleteCheckboxWidget or add one to RemovableFileFormWidget to customize the rendering. UPDATE: 5. April 2009. Making it work with latest Django (thanks for the comments).

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

Manager introspecting attached model

[A comment on a recent blog entry of mine](http://www.b-list.org/weblog/2008/feb/25/managers/#c63422) asked about a setup where one model has foreign keys pointing at it from several others, and how to write a manager which could attach to any of those models and query seamlessly on the relation regardless of what it's named. This is a simple example of how to do it: in this case, both `Movie` and `Restaurant` have foreign keys to `Review`, albeit under different names. However, they both use `ReviewedObjectManager` to provide a method for querying objects whose review assigned a certain rating; this works because an instance of `ReviewedObjectManager` "knows" what model it's attached to, and can introspect that model, using [Django's model-introspection API](http://www.b-list.org/weblog/2007/nov/04/working-models/), to find out the correct name to use for the relation, and then use that to perform the query. Using model introspection in this fashion is something of an advanced topic, but is extremely useful for writing flexible, reusable code. **Also**, note that the introspection cannot be done in the manager's `__init__()` method -- at that point, `self.model` is still `None` (it won't be filled in with the correct model until a bit later) -- so it's necessary to come up with some way to defer the introspection. In this case, I'm doing it in a method that's called when the relation name is first needed, and which caches the result in an attribute.

  • managers
  • models
  • introspection
Read More

93 snippets posted so far.