Opened 11 years ago

Closed 11 years ago

#21637 closed Bug (invalid)

Defining objects of models having custom field without any parameter.

Reported by: ANUBHAV JOSHI Owned by: ANUBHAV JOSHI
Component: Database layer (models, ORM) Version: 1.6
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Tim Graham)

When we define any model, then we can create its object as obj=ModelClassName(). But when we define custom fields we just cannot do the same always. If we are using to_python() method, then it shows up error.

If a define my model as:

from django.db import models

class LField(models.Field):
    __metaclass__ = models.SubfieldBase
    def db_type(self, connection):
        return 'longtext'
    def to_python(self, value):
        return long(value)

class Person(models.Model):
    name = models.CharField(max_length=80, blank=True, null=True)
    something_else = LField()
class Person2(models.Model):
    name = models.CharField(max_length=80, blank=True, null=True)
    ph = models.CharField(max_length=80, blank=True, null=True)

Then it is not possible to define an object of Person type without giving parameters.
i.e.
p=Person() raises ValueError
p=Person2() works fine as it should like in case of any other class.

Change History (4)

comment:1 by ANUBHAV JOSHI, 11 years ago

Owner: changed from nobody to ANUBHAV JOSHI
Status: newassigned

comment:2 by Tim Graham, 11 years ago

Description: modified (diff)

comment:3 by ANUBHAV JOSHI, 11 years ago

C:\Python27\lib\site-packages\django\db\models\base.pyc in init(self, *args, kwargs)

403 setattr(self, field.name, rel_obj)
404 else:

--> 405 setattr(self, field.attname, val)

406
407 if kwargs:

C:\Python27\lib\site-packages\django\db\models\fields\subclassing.py in set
self, obj, value)

33
34 def set(self, obj, value):

---> 35 obj.dict[self.field.name] = self.field.to_python(value)

36
37 def make_contrib(superclass, func=None):

C:\anubhav_imp\django_projects\dev\test1\models.pyc in to_python(self, value)

6 return 'longtext'
7 def to_python(self, value):


9

10 class Person(models.Model):

ValueError: invalid literal for long() with base 10:

comment:4 by Tim Graham, 11 years ago

Resolution: invalid
Status: assignedclosed

The to_python method must handle empty values (string/None) as documented here:
https://docs.djangoproject.com/en/1.6/howto/custom-model-fields/#django.db.models.Field.to_python

Note: See TracTickets for help on using tickets.
Back to Top