title: Django model with foreign key throws error on save
body: <p>I have a model with a foreign key that throws an error when I try to create a new object. I believe that the foreign key field (user_profile_id) is NULL for some reason (it shouldn't be), and when attempting to create, the error is thrown (the field should never be null). This is the error I get:</p>
  <pre><code>IntegrityError at /api/sensors/
  
  NOT NULL constraint failed: sensors_api_sensor.user_profile_id
  
  Request Method:     POST
  Request URL:    http://127.0.0.1:8000/api/sensors/
  Django Version:     2.2
  Exception Type:     IntegrityError
  Exception Value:    
  
  NOT NULL constraint failed: sensors_api_sensor.user_profile_id
  
  Exception Location:     /home/vagrant/env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 383
  Python Executable:  /home/vagrant/env/bin/python3
  Python Version:     3.6.9
  Python Path:    
  
  ['/vagrant',
   '/usr/lib/python36.zip',
   '/usr/lib/python3.6',
   '/usr/lib/python3.6/lib-dynload',
   '/home/vagrant/env/lib/python3.6/site-packages']
  
  Server time:    Mon, 21 Dec 2020 08:29:01 +0000
  </code></pre>
  <p>models.py:</p>
  <pre><code>class Sensor(models.Model):
  &quot;&quot;&quot;Database model for users' sensors&quot;&quot;&quot;
  
  user_profile = models.ForeignKey(
      settings.AUTH_USER_MODEL, # first argument is the remote model for this foreign key
      on_delete=models.CASCADE  # if ForeignKey is deleted, delete all associations
  )
  name = models.CharField(max_length=255)
  sensor_type = models.CharField(max_length=255)
  surrounding = models.CharField(max_length=255) 
  latitude = models.FloatField()
  longitude = models.FloatField()
  created_at = models.DateTimeField(auto_now_add=True, null=False) # auto adds creation timestamp UTC for each object
  updated_at = models.DateTimeField(auto_now=True, null=False)
  
  
  
  # other fields required
  REQUIRED_FIELDS = ['user_profile','name','type','surrounding']
  
  # model to string conversion method
  def __str__(self):
      &quot;&quot;&quot;Return the model as a string&quot;&quot;&quot;
      return self.name # returns the sensor name
  </code></pre>
  <p>serializers.py</p>
  <pre><code>class SensorSerializer(serializers.ModelSerializer):
  &quot;&quot;&quot;Serializes a sensor object&quot;&quot;&quot;
  
  class Meta:
      # points serializer to WeatherSensor model
      model = models.Sensor
      # list fields you want to make accessible from WeatherSensor model in tuple
      fields = ('id', 'user_profile', 'name', 'sensor_type', 'surrounding',
                'latitude', 'longitude', 'created_at', 'updated_at')
      # make foreign key read only by using extra keyword args variable
      extra_kwargs = {'user_profile': {'read_only': True}}
  </code></pre>
  <p>views.py</p>
  <pre><code>class SensorListApiView(APIView):
  &quot;&quot;&quot;Sensor List API View for list and create&quot;&quot;&quot;
  serializer_class = serializers.SensorSerializer
  
  def post(self, request):
      &quot;&quot;&quot;Create a weather sensor&quot;&quot;&quot;
      # self.serializer_class comes with APIView that retrieves serializer class for our review
      serializer = self.serializer_class(data=request.data)
      # validate input as per serializer class spec
      if serializer.is_valid():
          # can retrieve any field that is defined in our serializer
          serializer.save()
          return Response(serializer.data, status=status.HTTP_201_CREATED)
      else:
          # use status library to pass human-readable error
          return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  </code></pre>
  <p>settings.py</p>
  <pre><code>...
  # Model Overrides
  AUTH_USER_MODEL = 'profiles_api.UserProfile'
  </code></pre>
  <p>When testing a few weird things I observe:</p>
  <ol>
  <li>When testing locally in the browser using modheader for the authtoken, I get the above error when I submit</li>
  <li>In Django Shell, serializer is valid, but when I save the serializer I get the above error</li>
  <li>In Django Shell, I can successfully create the object using the below code:</li>
  </ol>
  <pre><code>user = models.UserProfile.objects.get(id=1)
  ws = models.Sensor.objects.create(
      user_profile=user, name='MoistureSensor1', 
      sensor_type='MoistureSensor', surrounding='greenhouse',
      latitude=37.7749, longitude=122.4194, 
      created_at=timezone.now(), updated_at=timezone.now()
  )
  ws.save()
  </code></pre>