Login

Tag "models"

Snippet List

Custom model field to store dict object in database

**Disclaimer** This is proof of concept snippet, It can not be considered as best practice. Seems like it's better to store (key => value) in sepetare model with 'key' and 'value' fields. **Example** You can assign any dict to model field that can be dumped/serialized with Django json encoder/decoder. Data is saved as TextField in database, empty dict is saved as empty text. Tested with Django 1.2beta. import DictionaryField class UserData(models.Model): user = models.ForeignKey(User) meta = DictionaryField(blank=True) There are similar snippets: [JSONField 1](http://www.djangosnippets.org/snippets/377/) or [JSONField 2](http://www.djangosnippets.org/snippets/1478/).

  • models
  • fields
  • json
Read More

SerializedObjectField

Model field that stores serialized value of model class instance and returns deserialized model instance. Example usage: from django.db import models import SerializedObjectField class A(models.Model): object = SerializedObjectField(serialize_format='json') class B(models.Model): field = models.CharField(max_length=10) b = B(field='test') b.save() a = A() a.object = b a.save() a = A.object.get(pk=1) a.object <B: B object> a.object.__dict__ {'field': 'test', 'id': 1}

  • django
  • models
  • fields
  • json
Read More

Context processor for django admin app_list

I never found a good snippet or tutorial to get the app_list (in django.admin) on other pages except the index page. So i started asking on irc j00bar has given me a very nice answer, but first i didn't know what to do with it till now. Anyways this snippet is very handy for the people who wants this but don't know how to get it. This is special made for the django version 1.1 Installation is quite easy, it is a context processor, so download this file put anywhere in your project, i got it in a app called cms_theme (theme and template related stuff.) and put the location in your settings.py file, example: `TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.request', '****cms.cms_themes.context_processors.theme', '****cms.cms_themes.context_processors.applist', )` The '****' stuff is nothing, i replaced my company name with it. Of course you may put the context processor anywhere else, that is your choice. Good luck! Alexander

  • django
  • models
  • admin
  • python
  • applications
  • app_list
  • app-models
Read More

Testrunner with testmodels

I miss the ability to use testmodels in app-tests. Using this testrunner you can include a test "app" in the app's tests module. Say if you have a module test_app.models within the tests module you could use it in the test like this: from django.test import TestCase from some_django_app.tests.test_app import models as testingmodels TEST_APPS = 'test_app' class ATestCase(TestCase): def test_no_url_model_signals(self): thing = testingmodels.ThingModel(name=u'a small thing') `TEST_APPS` can either be a string, a list or a tuple. This testrunner works with Django 1.1. It is based on the simple testrunner included with Django.

  • models
  • testrunner
Read More
Author: nfg
  • 0
  • 0

Model Choices Helper

This is my attempt at a convenience class for Django model choices which will use a [Small]IntegerField for storage. It's very similar to [jacobian's version](http://www.djangosnippets.org/snippets/1664/), but I wanted to be able to use simple attributes for access to the integer values. It's not technically dependent on Django, but it's probably not a datatype that would be useful for much else. Feel free to do so however if you have a use-case. >>> statuses = Choices( ... ('live', 'Live'), ... ('draft', 'Draft'), ... ('hidden', 'Not Live'), ... ) >>> statuses.live 0 >>> statuses.hidden 2 >>> statuses.get_choices() ((0, 'Live'), (1, 'Draft'), (2, 'Not Live')) This is then useful for use in a model field with the choices attribute. >>> from django.db import models >>> class Entry(models.Model): ... STATUSES = Choices( ... ('live', 'Live'), ... ('draft', 'Draft'), ... ('hidden', 'Not Live'), ... ) ... status = models.SmallIntegerField(choices=STATUSES.get_choices(), ... default=STATUSES.live) It's also useful later when you need to filter by your choices. >>> live_entries = Entry.objects.filter(status=Entries.STATUSES.live)

  • django
  • models
  • choices
Read More

OrderField

OrderField for models from http://ianonpython.blogspot.com/2008/08/orderfield-for-django-models.html and updated to use a django aggregation function. This field sets a default value as an auto-increment of the maximum value of the field +1.

  • models
  • fields
  • field
  • order
  • orderfield
  • integerfield
Read More

CSV Exporting of Model Data

This is a basic view for exporting data from models. It is designed so that you can provide the GET variables used for searching/filtering within listdisplay pages in the admin, and the code will filter the same way. It allows ouputting of model data in various formats using serializers. This should be used as a urlpattern through get_url, so that you can use the admin_view decorator to properly secure the data.

  • models
  • export
  • csv
  • data
  • reports
Read More

CSV Exporting of Model Data

This is a basic model view for exporting data from models. It is designed so that you can provide the GET variables used for searching/filtering within listdisplay pages in the admin, and the code will filter the same way. It allows the output of model data in various formats using serializers or templates.

  • models
  • export
  • csv
  • data
  • reports
Read More

decorator for method attribute assignment

A bit cleaner syntax for method attribute assignment; used in models for 'short_description'. >from mysite.polls.models import Poll >poll = Poll.objects.get(pk=1) >poll.was_published_today.short_description >>>'Published today?'

  • models
  • decorator
Read More

Custom model field for mysql time type.

Django does not have a suitable model field can process time type in mysql, the DateTimeField built-in django can not process more than 24 hours. That's why the code born. **Simply usage** `from myapp.models import TimeAsTimeDeltaField, SECONDS_PER_MIN, SECONDS_PER_HOUR, SECONDS_PER_DAY class EstimatedTime: days = None hours = None minutes = None seconds = None class Case(models.Model): estimated_time = TimeAsTimeDeltaField(null=True, blank=True) def get_estimated_time(self): estimated_time = EstimatedTime() if self.estimated_time: total_seconds = self.estimated_time.seconds + (self.estimated_time.days * SECONDS_PER_DAY) days = total_seconds / SECONDS_PER_DAY hours = total_seconds / SECONDS_PER_HOUR - days * 24 minutes = total_seconds / SECONDS_PER_MIN - hours * 60 - days * 24 * 60 seconds = total_seconds % SECONDS_PER_MIN estimated_time.days = days estimated_time.hours = hours estimated_time.minutes = minutes estimated_time.seconds = seconds return estimated_time else: return estimated_time

  • models
  • orm
  • database
  • field
  • timedelta
Read More

URL models

You can use `UrlModel` to provide URL functionality to any instance of any model and any language (language support can be removed from this). Each model must have own view method, that returns HttpResponse. I was inspired by Flatpages. It is useful for small sites and static pages. `class Page(UrlModel): text = models.TextField() def view(self, request) # do something here return HttpResponse(...)`

  • middleware
  • urls
  • models
  • foreignkey
  • model
  • generic
  • url
  • foreign-key
  • genericforeignkey
  • contenttypes
  • 404
  • contenttype
  • content-type
Read More

is_dirty and dict of changed values

When you call model.changed_columns() you get a dict of all changed values. When you call model.is_dirty() you get boolean whether or not the object has been changed since last save Based on an answer here:http://stackoverflow.com/questions/110803/dirty-fields-in-django but fixed and added is_dirty

  • django
  • models
  • save
  • dirty
Read More

Choices helper

A quick and dirty helper for model field `choices`. It's not perfect, but this is what I use.

  • models
  • choices
Read More

Improved model select field for generic relationships

Browse through the installed models using the content types framework. There are two difference in behavior with respect to the default field: 1. if a model provides a translation for its name (e.g.: verbose_name and/or verbose_name_plural), it shows that rather than a raw model name 2. allow to filter the models shown through the use of `choice` parameter Example: `mbf = ModelBrowseField(choices=['User', 'Session'])`

  • models
  • form
  • field
  • contenttypes
  • translation
  • browse
Read More

93 snippets posted so far.