Django: saving User object as ForeignKey only seems to work when dealing with the superuser, not sure if database or code causing the issue

StackOverflow https://stackoverflow.com/questions/18854638

Question

I am doing a django project where users submit ASCII art. My users are named 'Artists' and their creations are named 'Art', like so:

class Artist(models.Model):
    user        = models.OneToOneField(User)
    birthday    = models.DateField()
    name        = models.CharField(max_length=100)

def __unicode__(self):
    return self.name


class Art(models.Model):
    creator     = models.ForeignKey(User) 
    ...

def __unicode__(self):
    return self.title

(Where the 'user' attribute of the Artist refers to the default django User model.)

What I am trying to do at the moment is to create the art and have the current logged in user being recorded as the arts creator. This is a snippet of the view that is doing that:

from django.contrib.auth.models import User

def SubmitArt(request):

   art = Art(..., creator=request.user) 
   art.save()   

The problem with this is that this only seems to work when the initial superuser that I created at the start of my project is logged in. Every other user gives me this error when the submit form is completed:

IntegrityError at /submit/
insert or update on table "artapp_art" violates foreign key constraint "artapp_art_creator_id_fkey"
DETAIL:  Key (creator_id)=(3) is not present in table "artapp_artist".

My models used to read like this:

    creator     = models.ForeignKey('Artist') 

(which never worked) before I used south to change them. I am assuming this is a problem with my database, but I'm not sure how to fix it. I am using bitnami djangostack on a windows 7 machine. Thank you very much.

Was it helpful?

Solution

Can you verify that the artapp_art_creator_id_fkey foreign key constraint is not still pointing to Artist.id. That is what the error is stating. You may have forgotten to run the south migration, or south may have failed to change the constraint. You will need to look in the actual database to find out.

On another note, your original foreign key seems to make more sense to me. creator = models.ForeignKey('Artist') What is the reason you changed it to User? You would just have to make sure you pass an Artist to Art() rather than request.user.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top