ted
ted

Reputation: 14684

Why are my model restrictions ignored?

here is my model.py :

from django.db import models
class Code(models.Model):
    code = models.CharField(max_length=10)

    def __str__(self):
        return self.code

However when I enter the shell, this returns no mistake :

In [1]: from mini_url.models import Code

In [2]: co = Code()

In [3]: co.save()

In [4]: co = Code("1234567891011")

In [5]: co.save()

Whereas I expect two errors :

1/ from the fact that co is saved without any field, which is supposed to be impossible since there is no null = True

2/ from the fact that I save a Code whosecode field is longer than 10!

Any Idea?

Upvotes: 0

Views: 62

Answers (1)

Daniel Hepper
Daniel Hepper

Reputation: 29977

  1. The empty value of a CharField is the empty string ''.

  2. You do not actually set the code field. What your are actually doing is setting the id.

    >>> co = Code("1234567891011")
    >>> co.id
    "1234567891011"
    

    Try:

    co = Code(code="1234567891011")
    co.save()
    

    or, if you really do not want to use keyword arguments:

    co = Code(None, "1234567891011")
    

    It will raise an exception if you use a database that enforces length constraints (some databases, e.g. SQLite, don't).

Upvotes: 1

Related Questions