In my app I use auth0 to do authentication. Everything works great, I can see new users being created in admin panel etc, but there is one issue.
when I go to my endpoint that displays data I have an empty list. Like this
{
"id": "d458196e-49f1-42db-8bc2-ee1dba438953",
"owner": 1,
"name": "dsdsds",
"viewable": []
}
the list viewable is a list of users that can view the data object. So if you want to share your data with your friend you just add his email
Like I said previous. This list is viewable form django admin level and drf form level but not in JSON. How to display this data?
Models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
class User(AbstractUser):
pass
class WalletInstance(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
name = models.CharField(max_length=30, null=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE)
viewable = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='can_view', blank=True)
Settings.py
AUTH_USER_MODEL = 'budget_app.User'
SOCIAL_AUTH_TRAILING_SLASH = False
SOCIAL_AUTH_AUTH0_DOMAIN = '####'
SOCIAL_AUTH_AUTH0_KEY = '####'
SOCIAL_AUTH_AUTH0_SECRET = '####'
SOCIAL_AUTH_AUTH0_SCOPE = [
'openid',
'profile',
'email'
]
AUTHENTICATION_BACKENDS = {
'social_core.backends.auth0.Auth0OAuth2',
'django.contrib.auth.backends.ModelBackend'
}
LOGIN_URL = '/login/auth0'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
Serializers
class WalletInstanceSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.id')
class Meta:
model = WalletInstance
fields = '__all__'
depth = 1
CodePudding user response:
class WalletInstanceSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.id')
viewable = serializers.PrimaryKeyRelatedField(queryset=settings.AUTH_USER_MODEL.objects.all(), many=True)
class Meta:
model = WalletInstance
fields = '__all__'
depth = 1
CodePudding user response:
Update @TeRe answer. The settings.AUTH_USER_MODEL is a string, it has no attribute objects. You can use get_user_model docs:
from django.contrib.auth import get_user_model
class WalletInstanceSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.id')
viewable = serializers.PrimaryKeyRelatedField(queryset=get_user_model().objects.all(), many=True)
class Meta:
model = WalletInstance
fields = '__all__'
depth = 1