I have a problem that I hope someone with insight can aid with. My first Django project is near completion and I’m currently transitioning to a Postgres database in anticipation of deploying via Heroku. The process was going fairly smoothly until this occurred when I ran python manage.py syncdb.
django.db.utils.DatabaseError: relation “report_userprofile” does not exist
LINE 1: INSERT INTO “report_userprofile” (“user_id”, “first_name”, “…
Apparently, it did not create DB tables for the UserProfile model. I’m now getting this exception when I attempt to run the server:
Exception Type: DoesNotExist at /accounts/login/
Exception Value: Site matching query does not exist.
Among the additional apps I'm using for the project is django-profiles, which I had some issues setting up which are apparently common. The "Missing Manual" site – http://birdhouse.org/blog/2009/06/27/django-profiles/ – helped resolve those but may have led to the current problem.
I am using the signals.post_save.connect(create_profile, sender=User) recommended there. I was researching what might have gone wrong and came across this post on Google Groups and answer which states that “If you’re using a post_save signal on User you can’t do that because it results in a race condition." I’m wondering if this may be causing the issue and, obviously, what would be best to resolve it and get these tables into the new database and functioning.
Any insight into how to remedy this issue would be greatly appreciated.
This is the database model that may be causing the problem:
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True, related_name="profile")
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=35)
email = models.EmailField()
birth_date = models.DateField(blank=True, null=True)
city = models.CharField(max_length=25)
state = models.CharField(max_length=20)
zip_code = models.CharField(max_length=10)
profile_pic = models.ImageField(upload_to='profilepictures', blank=True)
def __unicode__(self):
return " %s" % (self.user)
def get_absolute_url(self):
return ('profiles_profile_detail', (), { 'username': self.user.username })
get_absolute_url = models.permalink(get_absolute_url)
signals.post_save.connect(create_profile, sender=User)
Something seems suspicious here:
INSERT INTO “report_userprofile” (“user_id”, “first_name”, “…
Those two fields are fields on the native User model, not fields on the custom Profile model. Why would it be trying to insert those fields into your Profile table?
Is there more code you're not showin here?
Looking around, I see some interesting alternative approaches to automatically creating Profile records:
http://djangosnippets.org/snippets/500/
http://www.turnkeylinux.org/blog/django-profile
But I know that the technique you're using (listed at Birdhouse) has worked well for every Django site I've built, so I'm not particularly suspicious of that.
Related
I've been building a Django website and included a UUID field "customer_id" in my initial "Customer" model. Finally, I decided to drop it. But when I try to delete it from my models.py, Django throws
SystemCheckError: System check identified some issues:
ERRORS:
<class 'accounts.admin.CustomerAdmin'>: (admin.E035) The value of 'readonly_fields[1]' is not a callable, an attribute of 'CustomerAdmin', or an attribute of 'accounts.Customer'.
Here is the code of models.py
from django.db import models
import uuid
# Create a base model to make sure we keep track of creation and edits
class ModelBaseClass(models.Model):
date_created = models.DateTimeField(auto_now_add=True, null=True)
date_modified = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
# Create your models here.
class Customer(ModelBaseClass):
customer_id = models.UUIDField(default=uuid.uuid4, #this is the field i try to drop
editable=False,
unique=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
What I tried so far:
I suspect that this could be related to existing data or some other dependencies. So...
I deleted the sqlite database, deleted all migration files and ran
"python manage.py makemigrations" and "python manage.py migrate".
I ran python manage.py flush.
I also tried to change the editable=False to editable=True and migrate before dropping,
but it didn't change anything.
It's perhaps also worth mentioning that my "Customer" model a relation to another model.
Could someone explain me why Django is preventing me from deleting this field and how to resolve this?
Thanks! :)
Could someone explain me what's going on and how to resolve this?
As the error says, you have a model admin named CustomerAdmin. Indeed:
<class 'accounts.admin.CustomerAdmin'>: (admin.E035) The value of 'readonly_fields[1]' is not a callable, an attribute of 'CustomerAdmin', or an attribute of 'accounts.Customer'.
For the readonly_fields, it lists the customer_id, but since that field is no longer available, it raises the error.
I have trouble to display the ''saved''/''liked'' posts of my users in django/admin. I would like to have a field in the Adminpage to show which user likes which posts. I made an Userprofile model where all extra information (besides the one on the given django admin user Profile) are stored. so here is my model View:
class UserProfile(models.Model):
user = models.OneToOneField(User, null=True)
#likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,default=1, related_name='likes')
likedPosts=models.ManyToManyField('self')
Field1 = models.CharField(max_length=50,default='Sunny')
Field2 = models.CharField(max_length=50,default='')
class Meta:
ordering =['-user']
#def __unicode__(self):
# return self.user.username
User.profile =property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
right now in the liked post field I have only some usernames or "User object"
I tried all kinds of combinations to get the information into the admin page but as you can see I did not make it.
I tried to change the unicode and of course the liked post line. If you need more information please tell me so. I appreciate every kind of help.
django admin isn't really meant to support many to many relationships from both directions in the django admin. However, the link below contains a workaround that I think should address your problem with a better explanation of why many-to-many relationships are only shown from one side by default.
(many-to-many in list display django).
so for everybody who wants to do something similar this worked for me:
class UserProfile(models.Model):
likedPosts = models.ManyToManyField('self',default=None,blank=True)
def __unicode__(self):
return "{0}".format(self.user.likes.all())
I am building a django web app with a custom user model. At the end of the sign up process when I submit the form an integrity error occurs.
Here is the error:
Exception Type: IntegrityError
Exception Value: NOT NULL constraint failed: accounts_user.job_history_id
This error indicates that the field in the custom user model named job_history cannot be null. However such a field does not even exist.
Here is my custom user model:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
avatar = models.ImageField(blank=True, null=True)
date_joined = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username", "password"]
def __str__(self):
return "#{}".format(self.username)
def get_short_name(self):
return self.username
I have no idea what this error is referring to and why it is occurring. I added the field named job_history at a previous point but have since deleted it and updated the database accordingly. This error only began to occur when I was fiddling around with the Job and User models in order to achieve a field capable of storing the users previously completed jobs. Further details are available in this stackoverflow questions.
Why is the integrity error occuring and how do I fix it?
The error says that your job_history field is still in the database and for some reason your migrations didn't work. So you need to look why your migration didn't work. You can try doing fake initial migration:
python manage.py makemigrations app_name
python manage.py migrate --fake-initial
I'm quite sure this should help, but if this also doesn't help you always can go directly to your DB and delete the job_history_id column from DB
This is a strange one. Maybe I missed it but I have search through all Django documentation and SF but could not find an answer for this. I have a table with about 30 columns. The table looks like this...
Class Customer (models.Model):
customer_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35)
middle_initial = models.CharField(max_length=2)
mail_addr1 = models.CharField(max_length=50)
mail_addr2 = models.CharField(max_length=50)
mail_city
mail_state
mail_zip
bill_addr1
bill_addr2
...
...
active_yn = models.ForeignKey('Status', models.DO_NOTHING) # <-- This one
...
...
home
mobile
The offending field is "active_yn". Django keeps spitting out an error saying that it is now a valid field.
Here's the things I am sure of:
The table definitely have this field in the correct DB, schema, table, etc
It is not the last field on the table.
inspectdb for this table is also missing this field.
I drop and re-add this column and it is still not showing.
The field is a TINYINT(3) - referencing a table Django recognized.
I am using MySQL
I have been trying to debug this for days now. Any ideas?
Thank you all for helping. I found the issue. The problem is on the DB side. I am using root user connecting directly to the DB. I have the settings file connecting with a different user with tables and fields granted to it. This table has this one field not in the grant to this user (Not my doing... urgh). Anyway, once I added this field, everything works as expected.
I appreciate all your help. Hopefully the next guy will find this useful.
Cheers!
I have my User model set up with no primary key so that the automatic id will be used instead. However, when I try to access it using Django's "_set" notation when it is referenced through a foreign key:
def postDetails(request, pk)
post = Post.objects.get(pk=pk)
if post.user_set.all(): # Errors on this line
[...]
I get an error from MySQL:
OperationalError at /webApp/postDetail/42/ (1054,
"Unknown column 'user.id' in 'field list'")
What am I doing wrong? Should I be accessing it differently? Are there limitations to the automatic id?
Model for reference:
class Post(models.Model):
name = models.CharField(max_length=128)
blog = models.ForeignKey('Blog')
active = models.BooleanField(blank=True)
created_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'post'
def __unicode__(self):
return self.name
class User(models.Model):
level = models.ForeignKey(Level)
post = models.ForeignKey(Post)
name = models.CharField(max_length=64)
note = models.CharField(max_length=4096)
active = models.BooleanField(blank=True, default=True)
class Meta:
managed = False
db_table = 'user'
Something else that I thought to include: I did run syncdb before running this.
EDIT : wrong answer. check comments below
The problem is that you have managed set to False. According to the documentation
If False, no database table creation or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed=False. All other aspects of model handling are exactly the same as normal. This includes
Adding an automatic primary key field to the model if you don’t declare it. To avoid confusion for later code readers, it’s recommended to specify all the columns from the database table you are modeling when using unmanaged models.
You will need to define the primary key as this is not done by default anymore.
Not 100% sure, but I think even though Django will add the id field to the model class, that field will not propagate to the DB with syncdb.
One way to try it would be to rename the existing User table, run syncdb and see if the User table is created. If not (which is likely because of the managed flag) try again with managed=True. If the id field appears in this case then my guess is you'll have to add it manually to the User table with the same parameters as the automatically created one.