I am using the Django REST Framework 2.0.
Here is my model class:
class Mission(models.Model):
assigned_to = models.ForeignKey('auth.User',
related_name='missions_assigned',
blank = True)
Here is my view class:
class MissionList(generics.ListCreateAPIView):
model = Mission
serialize_class = MissionSerializer
The multipart form is rendered in the browser with empty choice for
assigned_to
field.When posting raw JSON, I get the following error message:
Cannot assign None: "Mission.assigned_to" does not allow null values.
The
blank
option is used in the form validation, and thenull
is used when writing to database.So you might add
null=True
to that field.EDIT: continue the comment
Considering the two steps when saving object:
blank
)null
)For
default
option, takeIntegerField
for example,default=5, blank=True, null=False
, pass (1) even if you didn't assign a value(havingblank=True
), pass (2) because it has a default value(5) and writes5
instead ofNone
to DB.blank=True, null=False
, which pass (1) but not (2), because it attempts to writeNone
to DB.Thus, if you want to make a field optional, use either
default=SOMETHING, blank=True, null=False
orblank=True, null=True
.Another exception is the string-like field, such as
CharField
.It's suggested that use the
blank=True
alone, leavingnull=False
behind.This makes a field either a string(>=1 char(s)) or a empty string('', with len()==0), and never
None
.The reason is that when
null=True
is set, there will be two possible value for the state "unset": empty string andNone
, which is confusing(and might causing bugs).ForeignKey allows null values if this behavior was set. Your code will look like this:
You have to write null=True Note: after you change a model, you need to run
python manage.py makemigrations yourappname
and thenpython manage.py migrate