I have this error
jango.db.utils.IntegrityError: null value in column "user_id" of relation "defapp_actionlog" violates not-null constraint
DETAIL: Failing row contains (13, "{\"action\":\"push\"}", 2024-10-21 06:11:30.43758+00, 2024-10-21 06:11:30.43759+00, null).
What I want to do is push the actionlog from javascript and set the login user to model.
I set the CustomUser
object to user
row, however it still requies user_id
?
my viewset,model,serializer is like this below.
class ActionLogViewSet(viewsets.ModelViewSet):
queryset = m.ActionLog.objects.all()
serializer_class = s.ActionLogSerializer
def perform_create(self, serializer):
obj = serializer.save()
return obj
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
request.data._mutable = True
request.data['user'] = m.CustomUser.objects.get(id=request.user.id)
try:
serializer.is_valid(raise_exception=True)
except Exception as e:
logger.info(e)
self.perform_create(serializer)
return Response(serializer.data)
class ActionLog(models.Model):
user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='action_user')
detail = models.JSONField(default=dict,null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class ActionLogSerializer(ModelSerializer):
user = CustomUserSerializer(read_only=True,source="actionlog_user")
detail = serializers.CharField()
class Meta:
model = m.ActionLog
fields = ('id','user','detail')
Thanks to @Mohit Prajapat
I moved the def create
to serializer from view, now it works well.
class ActionLogSerializer(ModelSerializer):
user = CustomUserSerializer(read_only=True,source="actionlog_user")
detail = serializers.CharField()
class Meta:
model = m.ActionLog
fields = ('id','user','detail')
def create(self, validated_data):
validated_data["user"] = self.context["request"].user
obj = m.ActionLog.objects.create(**validated_data)
obj.save()
return obj
You are using ModalSerilizer here as I see, So you don't need to add id field explicitly in serializer. only the fields you want to customize should be there in serializer field while working with ModalSerilizer class