0

Below is the model named 'Dataset' containing three fields name, desc and data_file.

class Dataset(models.Model):
    name = models.CharField(max_length=256)
    desc = models.TextField()
    data_file = models.FileField(upload_to='datasets/')

I created a model object with python command.

>>> d = Dataset()
>>> d.save()
>>> d.name, d.desc, d.data_file
('', '', <FieldFile: None>)

Django allowed this object to be saved. Even when blank = False is the default for every field.

How can I may sure that dataset objects cannot be created with these three fields empty ?

Below is the sqlite3 schema:

CREATE TABLE IF NOT EXISTS "datasets_dataset"(
  "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  "name" varchar(256) NOT NULL,
  "data_file" varchar(100) NOT NULL,
  "desc" text NOT NULL
);
  • `blank` option is only validation related and `null` option is database related option. Try setting `blank=False` and `null=False`. And if you want any field to be filled by default if no value is provided then only set `default=`. – Ajay Lingayat Dec 30 '20 at 09:40
  • by default ```blank``` and ```null``` are False. And how can I set default value for a file field. – Hemant Mehra Dec 30 '20 at 09:46
  • Yes you can set default value for FileField. Check this : https://stackoverflow.com/questions/6740715/django-filefield-default-file – Ajay Lingayat Dec 30 '20 at 09:48
  • Thanks. But can there be a constraint so that Django throws raises an exception when saving empty objects ? – Hemant Mehra Dec 30 '20 at 09:51
  • Deliberately set `blank=False` in the field and if it doesn't work you can set your own validation to it : https://docs.djangoproject.com/en/3.1/ref/validators/ – Ajay Lingayat Dec 30 '20 at 09:56
  • Also you can check `FilePathField` in django models. Which is a CharField in a way but is used to store file paths. – Ajay Lingayat Dec 30 '20 at 09:57

0 Answers0