Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Foreign Key relation with User Table does not validate

Consider the following django model

from django.db import models                                                                                                                             
from django.contrib import auth
class Topic(models.Model):
   user = models.ForeignKey('auth.models.User')                                                                                                          
   name = models.CharField(max_length = NameMaxLength , unique = True)
   version_number = models.IntegerField(default = 0)
   created_at = models.DateTimeField(auto_now_add  = True)
   modified_at = models.DateTimeField(auto_now = True)
   update_frequency = models.IntegerField()

This model does not validate even after installing the auth_user table.

In [3]: auth.models.User.objects.all()
Out[3]: [<User: admin>]

The above statement is from django-admin shell

$ python manage.py syncdb
Error: One or more models did not validate:
topic: 'user' has a relation with model auth.models.User, which has either not
been installed or is abstract.

I am using django v1.0.4 with pinax 0.7.2 on ubuntu 11.04 , with sqlite3 database

The following Questions did not help much:

  • Foreign key to User table in django
  • How do I create a foreign key to the User table in Django?
like image 721
Gautam Avatar asked Sep 04 '11 01:09

Gautam


3 Answers

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

class Topic(models.Model):
    user = models.ForeignKey(User) 

'auth.User' would have worked, too. It's not Python's library syntax, it's the Django ORM's "app.model" syntax. But you should only pass the model as a string if you're desperately trying to solve a circular dependency. And if you have a circular dependency, your code is eff'd.

like image 132
Elf Sternberg Avatar answered Nov 11 '22 03:11

Elf Sternberg


Even I faced same issue,

The error message is clear: you haven't installed the User model.

Add "django.contrib.auth" to INSTALLED_APPS in your settings.py.

That all..Hope it will solve this issue, worked fine for me.

like image 26
Abdul Rafi Avatar answered Nov 11 '22 03:11

Abdul Rafi


I had the same error, but in different situation. I splitted the models.py in two files:

myapp/
    models/
        __init__.py
        foo.py
        bar.py

In foo.py I had two models:

class Foo(models.Model):
    attr1 = ... etc

class FooBar(models.Model):
    other = ... etc
    foo = models.ForeignKey(Foo)

    class Meta():
        app_label = 'foo'

I solved adding Meta also in Foo model:

class Foo(models.Model):
    attr1 = ... etc

    class Meta():
        app_label = 'foo'
like image 1
Griffosx Avatar answered Nov 11 '22 03:11

Griffosx