Question

I have a Post model with OneToOneField to a User model

class Post(models.Model):
    user = models.OneToOneField(User)
    title = models.CharField(max_length=255)
    content = models.TextField()
    date = models.DateField(auto_now_add = True)

    def __unicode__(self):
         return self.title

When I add a new post (using forms), everything is OK. But when I add the second post passing the same user, I get the UNIQUE constraint failed: socnet_post.user_id error.

I use a custom authentication backend:

from django.contrib.auth.models import User

class EmailAuthBackend(object):
    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(email=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

Exception goes from the post.save() line:

@login_required
def profile(request, username=None):
    context = RequestContext(request)

    if not username:
        username = request.user.username

    user = User.objects.get(username=username)
    posts = Post.objects.filter(user=user)

    context_dict = {'posts': posts}

    if request.method == 'POST':
        form = AddPostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()

    add_post_form = AddPostForm()
    context_dict['add_post_form'] = add_post_form
    return render_to_response('socnet/profile.html', context_dict, context)
Was it helpful?

Solution

It looks like you should use a foreign key instead of the one-to-one field as it's a one-to-many relationship (user can write many articles):

class Post(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=255)
    content = models.TextField()
    date = models.DateField(auto_now_add = True)

    def __unicode__(self):
         return self.title
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top