Login

Tag "model"

Snippet List

Encryption Fields

This provides some basic cryptographic fields using pyCrypto. All encryption/decription is done transparently and defaults to use AES. Example usage: class DefferredJunk(models.Model): semi_secret = EncryptedCharField(max_length=255)

  • model
  • field
  • encryption
Read More

keeping Model and Field History (everywhere)

Usage: class MyModel(ModelWithHistory): class History: model = True # save model changes into admin's LogEntry table fields = ('f1', 'f2') # save these fields history to AttributeLogEntry table f1 = CharField(max_length=100) f2 = IntegerField() for threadlocals, see http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser Aware! Not thoroughly tested yet. May cause problems with loading fixtures.

  • model
  • history
Read More

local django model test

Sometimes you need to test some model features without a complete django app installation. Just play only with the model object. With these small script you have a complete in memory django installation. Some Links: http://www.djangosnippets.org/snippets/1044/ (en) http://www.jensdiemer.de/permalink/150/mein-blog/99/django-db-model-test/ (de) http://www.python-forum.de/viewtopic.php?f=3&t=15649 (de) See also: https://github.com/readevalprint/mini-django/

  • model
  • testing
  • test
  • local-test
Read More

Copy a model instance

Create a copy of a model instance. Works in model inheritance case where ``instance.pk = None`` is not good enough, since the subclass instance refers to the parent_link's primary key during save. M2M relationships are currently not handled, i.e. they are not copied. See also Django #4027.

  • model
  • copy
Read More

ParentModel and ChildManager for Model Inheritance

This is the approach I've taken to access instances of child models from their parent. Functionally it's very similar to snippets [1031](http://www.djangosnippets.org/snippets/1031/) and [1034](http://www.djangosnippets.org/snippets/1034/), but without the use of `django.contrib.contenttypes`. Usage: class Post(ParentModel): title = models.CharField(max_length=50) objects = models.Manager() children = ChildManager() def __unicode__(self): return self.title def get_parent_model(self): return Post class Article(Post): text = models.TextField() class Photo(Post): image = models.ImageField(upload_to='photos/') class Link(Post): url = models.URLField() In this case, the `Post.children` manager will return a queryset containing instances of the appropriate child model, rather than instances of `Post`. >>> Post.objects.all() [<Post: Django>, <Post: Make a Tumblelog>, <Post: Self Portrait>] >>> Post.children.all() [<Link: Django>, <Article: Make a Tumblelog>, <Photo: Self Portrait>]

  • model
  • manager
  • queryset
  • inheritance
Read More

SQL Function Decorator

This decorator will replace a method on a model with a class method that executes SQL in the functions doc string.

  • sql
  • model
  • decorator
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

Command to make fixtures.

"Make fixture" command. Highly useful for making test fixtures. Use it to pick only few items from your data to serialize, restricted by primary keys. By default command also serializes foreign keys and m2m relations. You can turn off related items serialization with `--skip-related` option. How to use: python manage.py makefixture will display what models are installed python manage.py makefixture User[:3] or python manage.py makefixture auth.User[:3] or python manage.py makefixture django.contrib.auth.User[:3] will serialize users with ids 1 and 2, with assigned groups, permissions and content types. python manage.py makefixture YourModel[3] YourModel[6:10] will serialize YourModel with key 3 and keys 6 to 9 inclusively. Of course, you can serialize whole tables, and also different tables at once, and use options of dumpdata: python manage.py makefixture --format=xml --indent=4 YourModel[3] AnotherModel auth.User[:5] auth.Group

  • serialize
  • admin
  • model
  • fixtures
  • tests
  • test
  • management
  • commands
  • fixture
  • command
  • make
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

MarkdownTextField

A [common pattern in Django](http://code.djangoproject.com/wiki/UsingMarkup) is to create a TextField intended for Markdown text (i.e. description) and a companion non-editable TextField for storing the HTML version (i.e. description_html), so the Markdown converter need not be run for every page view. This snippet is a custom field which encapsulates this pattern in a single field which can automatically create and update its companion HTML field. Usage: class MyModel(models.Model): description = MarkdownTextField()

  • model
  • markdown
  • field
Read More

auto_now using signals

There has been some discussion about removing `auto_now` and `auto_now_add` some time ago. `auto_now_add` can be replaced be using a callable default value, `auto_now` can't. So I wrote this litte function for my current project (older ones still use `auto_add`) to fill the gap...but I'm not sure if `auto_now` will be removed at all.

  • datetime
  • model
  • auto_now
Read More

HTML color code field

A CharField (Model) that checks that the value is a valid HTML color code (Hex triplet) like #FFEE00.

  • model
  • db
  • color
  • hexcode
Read More
Author: b23
  • 1
  • 4

Enumeration field

These three classes allows you to use enumerations (choices) in more natural model-like style. You haven't to use any magic numbers to set/get field value. And if you would like to make your enumeration a full-fledged django-model, migration should be easy. Note, that you can subclass Item to add some context-specific attributes to it, such as `get_absolute_url()` method for instance. Examples are provided in the form of `doctest` in the second half of the snippet.

  • newforms
  • choice
  • model
  • field
Read More

Class ModelInfo for show object info

This class works in compatibility with a ModelForm, but instead of show a form, it shows the field values. The Meta class attributes can be used to customize fields to show, to be excluded, to divide by sections, to urlize text fields, etc. **Example 1:** class InfoSingleCertificate(ModelInfo): class Meta: model = SingleCertificate sections = ( (None, ('vessel','description','document','comments','status',)), ('Issue', ('issue_date','issue_authority','issue_location',)), ) **Example 2:** class InfoSingleCertificate(ModelInfo): class Meta: model = SingleCertificate fields = ('vessel','description','document','comments','status', 'issue_date','issue_authority','issue_location',) **How to use:** Just save this snippet as a file in your project, import to your views.py module (or a new module named "info.py") and create classes following seemed sytax you use for ModelForms.

  • forms
  • model
  • display
  • modelforms
  • info
  • values
Read More

137 snippets posted so far.