Login

Tag "models"

Snippet List

Specify a manager for the Admin

This example shows how you can easily limit the objects in the admin by specifying which Manager the admin should use. I haven't seen this documented anywhere (perhaps I've missed it), but it's proven extremely useful to me. The example here will limit objects to those that are attached to the current Site, but you can use any Manager you want (for example, a Manager that shows only published Articles). Finally -- not that I'm suggesting this -- but you *could* combine this with the ThreadLocals trick to show only objects that have been created by that user.

  • managers
  • models
  • admin
  • sites
Read More

Regrouping admin models

This is modification of Django's original adminapplist template tag. You can move your models from one app to other or completely hide them with this mod. Copy django_dir/contrib/admin/templates/admin/index.html file to your templates/admin folder, open it, then change {% load adminapplist %} to {% load custom_adminapplist %} (or whatever you named the templatetag file) After that, write your regrouping schema to settings.py file like this; UPDATED, now using tupples instead of dicts in APP_SCHEMA to make it more DRY. ` APP_SCHEMA=[ ( ['Model','List'], 'From App', 'To App', ), ( ['FlatPage'], 'Flatpages', 'Site Content', ), ( ['Product'] 'Product', 'Shop', ), ( ['Site'] 'Sites', #We are hiding Site model by not defining a target. ), ] `

  • templatetag
  • models
  • admin
  • app
Read More

Field map for models

It seems like one way or another I always need to get access to a specific field of a Model object. The current way to do this is to iterate through the object's _meta.fields list, comparing with the `name` attribute. Why not just have a lookup of fields? If you paste this code at the bottom of your models.py file it will add a `field_map` attribute to the meta options. For example: `profile = User.objects.get(id=1).get_profile()` `upload_to = profile._meta.field_map['image_icon'].upload_to` ...

  • models
  • fields
  • meta
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

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

"Link To" helper tag

Simple template tag that assumes some common conventions in order to quickly get a link to a specific model instance.

  • template
  • models
  • links
  • tags
  • anchors
Read More

UTC DateTime field

A DateTime field extension that automatically stores the timezone, and the computed UTC equivalent. This field needs the pytz library. The field adds two new fields to the model, with the same name of the UTCDateTimeField field, and a suffix. For an UTCDateTimeField named 'updated', the model will contain * an 'updated' field, which holds the local datetime * an 'updated_utc' field, which holds the corresponding UTC datetime * an 'updated_tz' field, which holds the field timezone name The timezone can vary between model instances, just set the 'xxx_tz' field to the desired timezone before saving. UTCDateTimeField supports a single optional keyword argument 'default_tz', in addition to the DateTimeField standard ones, to let the user choose a provider for a default timezone when no timezone has been set. Its value can be * None (or the argument missing), in which case the default settings.TIME_ZONE will be used * a callable, which will be called when the 'xxx_tz' field is emtpy, which should return a timezone name * a string, which will be used to access a model attribute or call a model method, which should return a timezone name If the timezone name points to a non-existent timezone, a warning will be issued and the default settings.TIME_ZONE value will be used. The field will also add three properties to the model, to access the pytz timezone instance, and the offset aware datetimes for local time and UTC. For the same 'updated' field instance we used above, the three properties added to the model will be: * updated_timezone * updated_offset_aware * updated_utc_offset_aware A brief example on how to use UTCDateTimeField: class UTCDateTimeTest(models.Model): """ >>> import datetime >>> d = datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) # new instance, tz from model method >>> t = UTCDateTimeTest(updated=d) >>> t.save() >>> t.updated datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) >>> t.updated_utc datetime.datetime(2007, 8, 24, 14, 46, 34, 762627) >>> t.updated_tz 'Europe/Rome' >>> t.updated_timezone <DstTzInfo 'Europe/Rome' CET+1:00:00 STD> >>> t.updated_offset_aware datetime.datetime(2007, 8, 24, 16, 46, 34, 762627, tzinfo=<DstTzInfo 'Europe/Rome' CEST+2:00:00 DST>) >>> t.updated_utc_offset_aware datetime.datetime(2007, 8, 24, 14, 46, 34, 762627, tzinfo=<UTC>) >>> """ updated = UTCDateTimeField(default_tz='get_tz') def get_tz(self): return 'Europe/Rome'

  • models
  • fields
  • datetime
  • timezone
  • field
  • utc
Read More

JSONField

This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript. **Example** (models.py): from django.db import models from jsonfield import JSONField class Sequence(models.Model): name = models.CharField(maxlength=25) list = JSONField() **Example** (shell): fib = Sequence(name='Fibonacci') fib.list = [0, 1, 1, 2, 3, 5, 8] fib.save() fib = Sequence.objects.get(name='Fibonacci') fib.list.append(13) print fib.list [0, 1, 1, 2, 3, 5, 8, 13] fib.get_list_json() "[0, 1, 1, 2, 3, 5, 8, 13]" *Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.

  • models
  • model
  • json
  • db
  • field
  • json-field
Read More

Querying on existence of a relationship

When you have two models joined by a foreign key, it's common to want to retrieve a set of objects from the "target" of the foreign key based on whether there are any objects "pointing" to them. This snippet demonstrates how to do so, using the `extra` method of the default model manager. Note that this is probably more efficient than using two ORM methods (e.g., selecting all values from one table, and using an `id__in` lookup on the other) since it does the whole thing in one query and avoids instantiating any intermediate objects.

  • models
  • orm
  • foreign-keys
Read More

common model privacy

A BooleanField indicating privacy is common on models, but the name of the field and whether the field being True indicates private or public both may change across models. If there is more than one potentially private model, a common interface is needed. A commonly-named method would do the job with `[a for a in MyModel.objects.all() if not a.is_private()]`, but it would still retrieve private instances from the database only to filter them out. This approach puts the name of the privacy field and whether that field being True indicates private or public in a tuple attribute of the model class. A chainable method is added to all QuerySet objects. example use: class MyModel(models.Model): is_public = models.BooleanField(default=True) # ... privacy_field = ("is_public", False) \>\>\> publicMyModels = MyModel.objects.all().exclude_private() \>\>\> values = publicMyModels.values()

  • models
  • querysets
Read More

DRY with common model fields (another way)

Some time you want to add some common fields to a group of models, for example, in a **Generalization/Specialization** relationship. One could have a base model as the generalization class and specialized models with a foreign key to that base model with an unique attribute but I don't like it that way so, I just do this code to add some commons attributes to a lot of models. If you have many models that all share the same fields, this might be an option. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your **python** code. This code is a cleaner way(I think!!!) to do it and will do the same that [this one](http://www.djangosnippets.org/snippets/317/). I hope this piece of code will be useful for you.

  • models
  • model
  • dry
  • common
Read More

"Approved" field with timestamp

I wanted to make the objects of a particular model approvable and store the timestamp of when that happened. In other frameworks/languages, I used to combined those in one "approved_at" field, which would be NULL if an object was currently unapproved. I tried different approaches to implement this in django, and this is the best I came up with so far. Basically, the code in __setattr__ makes sure that the field, once set, will not be updated again. Overriding setattr__() could also be a solution to determining if a field value has changed in save(), a question that seems come up from time to time in #django.

  • newforms
  • models
  • fields
  • forms
  • save
Read More

DRY with common model fields

If you have many models that all share the same fields, this might be an option. Please note that order matters: Your model need to inherit from TimestampedModelBase first, and models.Model second. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your python code. Not sure if there is a way to automate the call to TimestampedModelInit(). Tested with trunk rev. 5699. There is probably a slight chance that future revisions might break this.

  • models
  • model
  • inheritance
Read More

Filter to resize a ImageField on demand

A filter to resize a ImageField on demand, a use case could be: ` <img src="object.get_image_url" alt="original image"> <img src="object.image|thumbnail" alt="image resized to default 200x200 format"> <img src="object.image|thumbnail:"200x300" alt="image resized to 200x300"> ` The filter is applied to a image field (not the image url get from *get_image_url* method of the model), supposing the image filename is "image.jpg", it checks if there is a file called "image_200x200.jpg" or "image_200x300.jpg" on the second case, if the file isn't there, it resizes the original image, finally it returns the proper url to the resized image. There is a **TODO**: the filter isn't checking if the original filename is newer than the cached resized image, it should check it and resize the image again in this case.

  • filter
  • models
  • thumbnail
  • resize
  • imagefield
Read More

93 snippets posted so far.