'project.Account' has no ForeignKey to 'project.Object': How to link an account model to the objects of a project?

I am trying to create an announcement website (All) that can be visible to others (the Users, for which I added an Account). For this I wanted to modify a little the user profile to add fields like telephone, email address...

So I modified admin.py:

from django.contrib import admin
from .models import Todo, Account
from django.contrib.auth.models import User

class AccountInline(admin.StackedInline):
    model = Account
    can_delete = False
    verbose_name_plural = 'Accounts'

class TodoAdmin(admin.ModelAdmin):
    readonly_fields = ('created',)
    inlines = (AccountInline, )

admin.site.unregister(User)
admin.site.register(Todo, TodoAdmin)

But got back:

<class 'todo.admin.AccountInline'>: (admin.E202) 'todo.Account' has no ForeignKey to 'todo.Todo'.

So I added a ForeignKey to Todo with account = models.ForeignKey(Account, on_delete=models.CASCADE):

from django.db import models
from django.contrib.auth.models import User

class Account(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    email = models.CharField(max_length=100)
    firstname = models.CharField(max_length=30)
    lastname = models.CharField(max_length=50)
    company = models.CharField(max_length=5)

    def __str__(self):
        return self.user.username

class Todo(models.Model):
    title = models.CharField(max_length=100)
    datetime = models.DateTimeField()
    memo = models.TextField(blank=True)
    created = models.DateTimeField(auto_now_add=True)
    datecompleted = models.DateTimeField(null=True, blank=True)
    important = models.BooleanField(default=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    account = models.ForeignKey(Account, on_delete=models.CASCADE)


    def __str__(self):
        return self.title

But I still have the error.

  1. You accidentally wrote unregister for Users in your admin.py file. It should be admin.site.register(User)
  2. You misinterpretted the error: the error states that you don't have a foreign key in your Account model to Todo.

This means your inline admin code isn't correct as it's expecting the other way around.

Back to Top