Django admin : How to show a model as inline inside another model, which is indirectly related

40 views Asked by At

I have models named user, authtoken and userdevice.

class User(LifecycleModelMixin, AbstractUser):
    email = models.EmailField(unique=True)
    slug = models.SlugField(max_length=100, unique=True, blank=False, null=True)



 class AuthToken(models.Model):
        objects = AuthTokenManager()
        digest = models.CharField(
            max_length=CONSTANTS.DIGEST_LENGTH, primary_key=True)
        token_key = models.CharField(
            max_length=CONSTANTS.TOKEN_KEY_LENGTH, db_index=True)
        user = models.ForeignKey(User, null=False, blank=False,
                                 related_name='auth_token_set', on_delete=models.CASCADE)
        created = models.DateTimeField(auto_now_add=True)
        expiry = models.DateTimeField(null=True, blank=True)

class UserDevice(models.Model):
    token = models.OneToOneField(AuthToken, on_delete=models.CASCADE, related_name="auth_token")
    device_type = models.CharField(max_length=100, choices=DevicesChoices.choices)
    access_type = models.CharField(max_length=100, choices=AccessChoices.choices)
    device_brand = models.CharField(max_length=100, null=True, blank=True)

I need to show the userdevice inside the user detail page in admin panel as inline.

Django Error admin.E202 'userdevice' has no ForeignKey to 'accounts.user'

Getting this error. Any help will be much appreciated.

1

There are 1 answers

0
Danijel On

You need to link User model to UserDevice model.

models.py

class UserDevice(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE)
   token = models.OneToOneField(AuthToken, on_delete=models.CASCADE, related_name="auth_token")
   device_type = models.CharField(max_length=100, choices=DevicesChoices.choices)
   access_type = models.CharField(max_length=100, choices=AccessChoices.choices)
   device_brand = models.CharField(max_length=100, null=True, blank=True

admin.py

from django.contrib import admin

class UserDeviceInline(admin.TabularInline):
   model = UserDevice
   extra = 0

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
   list_display = ['email', 'slug']
   inlines = [UserDeviceInline]

Now in User Details you have Device info. More info