Login

Tag "model"

Snippet List

JSONable model base

This is a basic stub for a model that you can use to easily add customizable JSON serialization to your models. Make your model inherit from JsonableModel, and then define the models/yourmodel.json template with whatever information from the model that you want to make available.

  • model
  • json
  • inherit
Read More

ManyToManyField no syncdb

**Sumary** M2M relation without creating table. Normally you should specify m2m only in *one* model, thus widgets for many-to-many relations will be displayed inline on whichever model contains the actual reference to the ManyToManyField. But if you want to be able to have widgets displayed on both form you need some tricks, for example using intermediary-models can help, but you will not get multiselect widget (and in case of inlining extra = multi). Also you can write your own form which takes care about adding widget (just 1 line) and setting default values and saving it (more than few lines of code). If you try ManyToManyField with same db_table specified, the only problem will be in syncdb (it will try to create two identical tables) and the only thing our class does is preventing creation of table for M2M, so in one model you should use ManyToManyField and in another ManyToManyField_NoSyncdb with the same db_table argument. **Example** So to have M2M widgets in both forms you can write: class User(models.Model): #... groups = ManyToManyField('Group', related_name='groups', db_table=u'USERS_TO_GROUPS') class Group(models.Model): #... users = ManyToManyField_NoSyncdb(User, related_name='users', db_table=u'USERS_TO_GROUPS')

  • model
  • field
  • manytomany
  • manytomanyfield
  • syncdb
Read More

Dynamic growing model

This model is designed for my webshop. The Client-object is very 'stretch-able' by defining more fields to the client. These extra fields ares stored in the ClientConfig-object. Be sure to create a new Client-instance first and SAVE it! Without a client.id the ClientConfig won't work.

  • django
  • dynamic
  • model
  • example
  • client
Read More

UnicodeReprMixIn

Add's updated and created fields to a model if mixed in. Example that uses the name as the representation: class Company(models.Model, UnicodeReprMixIn): """ A representation of a comic book company. """ name = models.CharField(max_length=255) slug = models.SlugField() logo = models.ImageField(upload_to=os.path.join('upload', 'company_logos')) url = models.URLField(verify_exists=True) _unicode = "name"

  • model
  • unicode
  • orm
  • mixin
  • __unicode__
Read More

Clone model mixin

Add this as a superclass of any Django model to allow making copies of instances of that model: class Entry(models.Model, CloneableMixin): [...] e = Entry.objects.get(...) e_clone = e.clone() e_clone.title = 'Cloned Entry' e.save() The new object is saved during the clone process and ManyToMany relations are copied as well.

  • model
  • mixin
  • copy
  • clone
  • clonable
Read More

uuid model field

This code provides a primary key field that is globally unique. It uses the pre_save method to auto-populate the field with a Universal Unique Id as the record is saved the first time.

  • model
  • field
  • uuid
  • universally-unique-identifier
Read More

Clear nullable foreign keys on delete

Django 1.0 is apparently hard-coded for cascading deletes. I find that I often have nullable foreign keys on models whose records must not be deleted along with those they refer to. I override Model.delete() in an intermediate base class and execute this method to clear out all nullable foreign keys before allowing a delete to proceed.

  • model
  • delete
  • cascade
Read More

Model Forms: Clean unique field

Often I want fields in my models to be unique - Django's `unique` works too late in model form validation and will throw an exception unless you check for it by hand. This is a bit of code that cleans up the boiler plate of checking if different fields are unique. Set `exclude_initial` to `False` if you want to raise an error if the unique field cannot be set to whatever value the instance had before. **Update** Thanks fnl for rightly pointing out that Django's `unique=True` does check for this - just make sure to pass `instance=obj` when you're initializing your forms. _HOWEVER_ a problem you'll typically run into with this is though you want a field to unique, you also want multiple entries to be able to be `blank`. This can help you!

  • forms
  • model
  • unique
  • model-forms
Read More

Multiple Choice model field

Usually you want to store multiple choices as a manytomany link to another table. Sometimes however it is useful to store them in the model itself. This field implements a model field and an accompanying formfield to store multiple choices as a comma-separated list of values, using the normal CHOICES attribute. You'll need to set maxlength long enough to cope with the maximum number of choices, plus a comma for each. The normal get_FOO_display() method returns a comma-delimited string of the expanded values of the selected choices. The formfield takes an optional max_choices parameter to validate a maximum number of choices.

  • multiple
  • model
  • form
Read More

Child aware model inheritance

Base models aren't aware of its inherited models, here is a quick solution to access child models from the base model.

  • model
  • inheritance
  • child
  • content-type
Read More
Author: rix
  • 2
  • 4

Address model

This is standart address model. Must match US / GB / French address and other... Specifics locales fields are notice by comments.

  • model
  • address
Read More

MarkupTextField

I updated [MarkdownTextField](http://www.djangosnippets.org/snippets/882/) to have some choices in markup. It currently support for Markdown, Textile, Plain Text, and Plain HTML. It will add `%s_html` for the complied HTML and `%s_markup_choices` for a drop down of markup choices. Usage: class MyModel(models.Model): description = MarkupTextField()

  • model
  • markup
  • markdown
  • textile
  • field
Read More

update_or_create

Django provides a `get_or_create` helper method in the `models.Manager` class which looks up an object for the given `kwargs`, creating one if necessary. But sometime you need a method which updates the object with given `kwargs` or creates it if it's not found. This snippet provides the helper for that purpose. Use the snippet like this: from django.db import models class PersonManager(models.Manager): update_or_create = _update_or_create class Person(models.Model): first_name = models.CharField() last_name = models.CharField() city = models.CharField() objects = PersonManager() person, created, updated = Person.objects.update_or_create(first_name="John", last_name="Smith", defaults=dict(city="London")) The method returns a tuple of (`object`, `created`, `updated`), where `created` and `updated` are booleans specifying whether an `object` was created or updated respectively. Both `created` and `updated` are `false` if `object` is neither created nor updated (that is `object` has just been fetched "as is" from db). This happens if the update fails.

  • model
  • helper
  • update
  • create
Read More

Django JQuery Autocomplete for Model Selection

This is a general JQuery Autocomplete Form Field for selecting any model instance in your forms. 1 Download jquery.1.2.6 and the jquery autocomplete plugin http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/, place theme somewhere in your media directory (in this case {{ MEDIA__URL}}/js/ 2 copy fields.py to anywhere in your python-path (in this case utils.fields) 3 create a view for the ajax request that receives a query and returns a key|value list, and register it in your urls.py 4 Just Use the fields in any form like in forms.py

  • selection
  • model
  • jquery
  • autocomplete
Read More

137 snippets posted so far.