Login

Subclassing a model.field for newforms

Author:
chasfs
Posted:
March 28, 2007
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

The newforms fields are more capable than the django models fields. In this snippet, we subclass models.IntegerField, and add min_value and max_value.

e.g. age = MMIntegerField('How old are you?', min_value=13, max_value=120)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.db import models

class MMIntegerField(models.IntegerField):
  "Min Max Integer Field - use in place of models.IntegerField"
  def __init__(self, verbose_name=None, min_value=None, max_value=None, **kwargs):
    self.min_value = min_value
    self.max_value = max_value
    models.IntegerField.__init__(self, verbose_name, **kwargs)
    
  def formfield(self, **kwargs):
    return models.IntegerField.formfield(self,  min_value=self.min_value, max_value=self.max_value, **kwargs)
    
  def get_internal_type(self):
        return "IntegerField"  
  

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.