4

In the code below, somehow the fields that have blank=True are still required and cannot be Null

Example:

# Skill train timer
    class SkillTrainingTimer(models.Model):
    """
    Character Training timer,  keep track fo what skill is in training, and when it is done
    """
    character = models.ForeignKey(Character, unique=True)
    skill = models.ForeignKey(Skill, blank=True)
    trainingground = models.ForeignKey(TrainingGround, verbose_name='Training ground')
    timer = models.DateTimeField()

and now i do:

train_skill = SkillTrainingTimer(
        character=some_character_obj,
        trainingground=some_trainingground_obj,
        timer = fatetime.datetime.now()
)
train_skill.save()

It starts complaining skill cannot be Null. I have this in a lot of models and functions and so far i just dumped some useless data in it.

codegeek
  • 32,236
  • 12
  • 63
  • 63
Hans de Jong
  • 2,030
  • 6
  • 35
  • 55

3 Answers3

4

null=True sets NULL on the column in your DB.

blank=True determines whether the field will be required in forms. This includes the admin and your own custom forms. If blank=True then the field will not be required, whereas if it's False the field cannot be blank. Hope this helps!

Arovit
  • 3,579
  • 5
  • 20
  • 24
3

You have to add the null=True argument on the field definition, preferably before a syncdb (or you can migrate with South)

skill = models.ForeignKey(Skill, blank=True, null=True)
Steve K
  • 10,879
  • 4
  • 39
  • 39
2

For a foreign key, there isn't really a valid blank value other than NULL. Effectively, on the database side, you need to either enter NULL, or some valid value for that foreign key.

So, to allow the foreign key to be entered, you also need to add null=True. This will enter blank values as NULL into the database, as specified in the documentation.

However, a simple blank=True is recommended for fields like models.String, where there is another blank value other than NULL, i.e., the empty string. This allows you to use NULL where you want to, say, differentiate a field that has never been filled, from a field that has been filled in with a blank value. The distinction is slim, and it will usually not be necessary, but it is possible to have as a requirement (although it's not recommended in the documentation).

Hannele
  • 9,301
  • 6
  • 48
  • 68