Sindhujit
Sindhujit

Reputation: 51

Django - Object of type User is not JSON serializable

I am facing an issue with POSTing data (which has a User object) to a ModelViewSet. Error: "Object of type User is not JSON serializable"

data_params = {
        "log_user_id": user,
        "device_name": "sampledevice",
        "log_user_email": "svc.netadc@ads.aexp.com",
        "feature_name": 'Subnet Automation',
    }

    print(data_params, "data_params")
    response = requests.post("<url>/netadc3/arista/ImplementationLogsAristaViewSet/implementationlogsarista/",
    auth=(<username>, <password>), headers={"content-type": "application/json"}, data=json.dumps(data_params), verify=False)

serializers.py:

class ImplementationLogsAristaSerializer(serializers.HyperlinkedModelSerializer):

    log_user_id = UserSerializer(read_only=True)

    class Meta:
        model = ImplementationLogsArista
        fields = ('log_id','device_name', 'log_user_id','log_user_email','feature_name')

views.py:

class ImplementationLogsAristaViewSet(viewsets.ModelViewSet):
    queryset = ImplementationLogsArista.objects.all()
    serializer_class = ImplementationLogsAristaSerializer
    permission_classes = (IsAuthenticated,)
    pagination_class = None

models.py:

class ImplementationLogsArista(models.Model):

log_id = models.AutoField(primary_key=True)
device_name = models.CharField(max_length=800, verbose_name='Device Name',default='sampledevice')
log_user_id = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, verbose_name='User ID')
log_user_email = models.CharField(max_length=500, verbose_name='User Email',default='admin')
feature_name = models.CharField(max_length=100, verbose_name='Feature Name',default='default_feature')

class Meta:
    verbose_name = 'Implementation/Backout Logs'
    verbose_name_plural = 'Implementation/Backout Logs'


def __unicode__(self):

    return '%s %s %s %s %s' % (self.log_id,self.device_name,self.log_user_id,self.log_user_email,self.feature_name)

Not sure how to successfully POST the data with User into the ModelViewSet.

Upvotes: 0

Views: 633

Answers (1)

akun.dev
akun.dev

Reputation: 339

Probably, your user is Django User model instance, which is not JSON serializable:

data_params = {
        "log_user_id": user, # <-- here
data=json.dumps(data_params) # <-- here 

You should put user.pk in data_params:

data_params = {
        "log_user_id": user.pk, # <-- here

Upvotes: 1

Related Questions