5

Go to edit 2

Calling the following adduser function in views.py. I save the user first because it's id (automatically created by Django upon INSERT) is the primary/foreign key for accounts and passwords. Adding a user seems to be working fine, but then when it gets to the Accounts(user=u), the following error throws:

IntegrityError at /adduser
insert or update on table "OmniCloud_App_accounts" violates foreign key constraint "user_id_refs_id_468fbcec324e93d2"
DETAIL:  Key (user_id)=(4) is not present in table "OmniCloud_App_user".

But the key should be there since it just saved the user to the db...

def adduser(request):
    username = request.POST['username']
    password = request.POST['password']
    u = User.objects.create_user(username, request.POST['email'], password)
    u.save()
    a = Accounts(user=u)
    p = Passwords(user=u)
    a.save()
    p.save()
    user = authenticate(username=username, password=password)
    if user is not None and user.is_active:
        auth.login(request, user)
        return HttpResponseRedirect("/%s/" %u.id)
    else:
        return HttpResponseRedirect("/account/invalid/")

EDIT: Here is the beginning to the initialization of Accounts:

from django.db import models
from django.contrib.auth.models import User
class Accounts(models.Model):   
    user = models.ForeignKey(User)

EDIT 2 I've realized, by going to the admin page, that when It complains that 4 isn't in the database, that is because it is adding the 3rd user. Adding the 4th user throws an error that there is no user with id 5 (duh). I don't see anything in the code that would cause it to search for user_id+1, any ideas

To the war chest!

5
  • what kind of object is Accounts?
    – second
    Nov 7, 2011 at 17:45
  • Accounts is a model like User just with a ton of different fields for social, media, & email usernames.
    – Chris
    Nov 7, 2011 at 20:05
  • u.save() is not needed since create_user() should already commit it to the database. You should probably show the user field in Accounts model. Do you have any user model of your own?
    – Lycha
    Nov 7, 2011 at 22:47
  • user = models.ForeignKey(User) The user model is the default from Django. Are you sure that create_user saves? I had issues earlier initializing all three tables at once then saving because it showed something similar, where pushing u.save() before the creation of Accounts or Passwords fixed it.
    – Chris
    Nov 8, 2011 at 2:17
  • Do you use the User model located in contrib.auth.models? Because the error says: 'OmniCloud_App_user' instead of 'OmniCloud_auth_user'
    – Willian
    Nov 15, 2011 at 22:50

4 Answers 4

4
+50

My money is on a misspelled name. I notice in the error message that you have

OmniCloud_App_accounts
OmniCloud_App_user

Second table uses singular. There isn't a second table like this by chance:

OmniCloud_App_users

Also, using mixed case identifiers in PostgreSQL is a great source of reputation here on SO. It will bite you sooner or later. Victims of that folly are regulars here. Any table with this name maybe - and you forgot the double quotes in "OmniCloud_App_user" somewhere?

omnicloud_app_user

It's either that or the transaction saving the user has not been committed yet. Can you only create the user (and no accounts yet) and check if it ends up in the right database in the table and with the right ID?

Edit: tools to diagnose the problem

If you know that users are being created, then the question is: does the foreign key constraint user_id_refs_id_468fbcec324e93d2 look at the right place? Same database? Same schema? Same table?

To find out which tables exists in your database, try the following query (if you have the necessary privileges):

SELECT n.nspname AS schema_name
      ,c.relname AS table_name
      ,c.relhastriggers
      ,c.reltuples
FROM   pg_catalog.pg_class c
LEFT   JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE  c.relname ~~* '%user%'
AND    c.relkind = 'r'
AND    nspname <> 'pg_catalog';

Shows all tables in all schemas that have "user" in the name, case insensitive. Plus if the table has triggers (could cause your problem) and how many rows are in it (estimate updated by ANALYZE). Might give you a lead ...

You can also use the meta-command \d of the standard command line client (interactive terminal) psql.

I would run a test case and have the postgres server log everything it gets. Set this parameter for that purpose:

set log_statement = 'all';

The manual about logging-parameters.

log_statement (enum)

Controls which SQL statements are logged. Valid values are none (off), ddl, mod, and all (all statements).

The manual on how to set parameters.

4
  • I will look into that shortly, but to answer you last question I know that users are being created because as I try to debug and test by refilling out the signup page, the Key (user_id)=(4) increments each time as it should, and attempting to signup the same username rejects as it should. So users are being added but not accounts.
    – Chris
    Nov 10, 2011 at 15:03
  • I added the initialization of Accounts there. User is a model that I did not declare (Django built in model). Does Django save it to the DB as Users, even thought you import User to use it?
    – Chris
    Nov 10, 2011 at 15:58
  • @Cris: I updated my answer with some help to analyze the problem. I can't help you much with Django internals. Not my area of expertise. Nov 10, 2011 at 17:17
  • The closest I can get to the answer is this. It may be that I used to have a custom user table that wasn't correctly deleted when installing the default Django one. Anyway, you gave a very thorough answer so happy bounty!
    – Chris
    Nov 17, 2011 at 4:29
0

I can't see anything wrong with the code you have provided that would cause that error, but there are a few things that you're doing differently from the recommended method

You seem to be using a ForeignKey relationship - that may not be what you want, unless you're planning on a single User being linked to multiple Accounts. A OneToOne relationship is probably what you want, unless this is the case.

Using a Handler to create the Account associated with the User seems like a better way to handle things as well - as django will deal with calling the handler, rather than you having to remember to call the appropriate code. Though whether that will fix your problem, I'm not so sure

This part of the manual suggests that you shouldn't need to call u.save() after calling create_user, unless you have altered the user since it was created.

0

Try decorating your function this way :

from django.db import transaction

 @transaction.autocommit
 def adduser(request):

django default with postgres is to start a transaction with the view and commit it at the end (exceptions are rollbacks).

so .saved() objects are not always the way you expect them...

1
  • so would I not call u.save since it would autosave?
    – Chris
    Nov 11, 2011 at 1:17
0

few comments Use OneToOneField in accounts modeland userprofile https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_profile and make a signal saving for account saving

you can use saving user in this way. Pylint say it's not good but the same way use inside of Django

try:
    user = User.objects.create(**request.POST) #better way save from forms, no the forms is best way 
except:
    #exception logic
    pass
else:
    auth.login(request, user)

so if you use forms

form = UserForm(request.POST or None)
if form.is_valid():
    user = form.save()
    auth.login(request, user)
else:
    #invalid data logic
    pass
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.