Quintiliano
Quintiliano

Reputation: 93

Django - <class> has no ForeignKey

I'm setting up Django admins with:

model.py

class Types(models.Model):
    types = models.CharField(max_length=60)

    def __str__(self):
        return self.type

class File(models.Model):
    file_name = models.CharField(max_length=60)
    type = models.ForeignKey(Types)

    def __str__(self):
        return self.file_name

class Set(models.Model):
    set_name = models.CharField(default='New Set', max_length=60)
    data = models.DateTimeField('Date of creation')
    file = models.ForeignKey(File)
    size = models.IntegerField(default=0)

    def __str__(self):
        return ("%s - %s" % (self.set_name, str(self.data)))

    class Meta:
        ordering = ["data"]

And at admin.py

class FileInline(admin.StackedInline):
    model = File
    extra = 2

class SetAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,      {'fields':['set_name']}),
        (None,      {'fields':['data']}),
        (None,      {'fields':['size']}),
    ]
    inlines = [FileInline]

admin.site.register(Set, SetAdmin)

With this I'm getting the following error:

(admin.E202) 'Disk.File' has no ForeignKey to 'Disk.Set'

According to documentation in https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey it was supposed to work.

I did some tests with: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-a-model-with-two-or-more-foreign-keys-to-the-same-parent-model but without sucess. Inverting the classes, making File with ForeignKey from Set also didn't work.

From Django tutorial I've managed to get the relationship working, but i'm falling at replicate it.

I've checked the suggestions on the following posts: Inline in Django admin: has no ForeignKey and Django - Inline (has no ForeignKey to) but i couldn't figure out what is wrong.

I'm using Python 2.7.6, Django 1.8.4, MySQL 5.6 and Ubuntu 14.04.

I would really appreciate any suggestion!

Upvotes: 2

Views: 5056

Answers (1)

user764357
user764357

Reputation:

Trimming back your code the problem is this - in your models you are saying :

A Set has one File, and a File has many Sets

But your admin file says:

A Set can have many Files

These are two contradictory statements. You need to make them match, either:

Fix your models:

class File(models.Model):
    # Add the below line
    file = models.ForeignKey(Set) 

class Set(models.Model):
    # Delete this line
    # file = models.ForeignKey(File)

Or fix your admin - which is a complete rewrite, and the above seems what you want anyway.

Upvotes: 3

Related Questions