Sebastian Olsen
Sebastian Olsen

Reputation: 10878

Cannot assign '1': Comment.user must be a user instance

... But it is!? I'm using Django 1.9 and Python 3.

I'm trying to let people comment on a post, my model looks like this:

class Comment(models.Model):
    user = models.ForeignKey(User, unique=False)
    post = models.ForeignKey(Post, unique=False)
    content = models.TextField(max_length=450)
    created = models.DateField(auto_now=False,auto_now_add=True)
    edited = models.BooleanField(default=False)
    replies = models.ManyToManyField('Comment', blank=True)
    score = models.BigIntegerField(default=0)

    def __str__(self):
        return self.content

I'm not using a form, instead I am trying to create the object in the view:

def PostView(request, user, slug):
    instance = get_object_or_404(Post, user__username=user, slug=slug)
    context = {
        'object': instance,
        'MEDIA_URL': MEDIA_URL,
        'STATIC_URL': STATIC_URL
    }

    if request.method == 'POST':

        data_type = request.POST.get('type')

        if data_type == 'comment':
            content = request.POST.get('content')
            author = get_user(request)
            author_id = author.id
            post = instance
            comment = Comment(user=author_id, post=post, content=content)

However this should work fine, but I get this really strange error when trying to POST a comment:

Cannot assign "1": "Comment.user" must be a "User" instance.

The error occurs when I'm trying to create the object. Full traceback can be seen here

Upvotes: 4

Views: 3230

Answers (1)

Alasdair
Alasdair

Reputation: 308829

You should assign a User to the Comment.user field. You are currently assigning the id instead. You can either do:

comment = Comment(user=author, post=post, content=content)

or

comment = Comment(user_id=author_id, post=post, content=content)

Upvotes: 4

Related Questions