Django getting an integrity error, for hitting a not null exception

I have this model

class ConversationMessage(models.Model):
    conversation = models.ForeignKey(Conversation, related_name='messages', on_delete=models.CASCADE)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add = True)
    created_by = models.ForeignKey(User, related_name='created_messages', on_delete=models.CASCADE)

It is used in this form

class ConversationMessageForm(forms.ModelForm):
    class Meta:
        model = ConversationMessage
        fields = ('content', )
        widgets = {
            'content': forms.Textarea(attrs = {
                'class': 'w-full py-4 px-6 rounded-xl border'
            })
        }

And in this view it gets saved/submitted,

def new_conversation(request, item_pk):
    item = get_object_or_404(Item, pk = item_pk)

    if item.created_by == request.user:
        return redirect('dashboard:Dashboard-Page')

    conversation = Conversation.objects.filter(item = item).filter(members__in=[request.user.id])

    if conversation:
        pass # redirect to conversation if it already exists

    if request.method == 'POST':
        form = ConversationMessageForm(request.POST)

        if form.is_valid():
            conversation = Conversation.objects.create(item=item)
            conversation.members.add(request.user)
            conversation.members.add(item.created_by)
            conversation.save()

            conversation_message = form.save(commit=False)
            conversation_message.conversation = conversation
            conversation.created_by = request.user
            conversation_message.save()

            return redirect('item:Item-Detail', pk = item_pk)
    else:
        form = ConversationMessageForm()

and the user is logged in, as request.user works in the previous line

if item.created_by == request.user:
      return redirect('dashboard:Dashboard-Page')

but for some reason in this line

conversation.created_by = request.user

conversation.created_by becomes null

But i get this error

Exception Type: IntegrityError
Exception Value: NOT NULL constraint failed: conversation_conversationmessage.created_by_id

It’s because you’re setting created_by and not saving it.

See:

The save call was done before:

You can move the line that sets created_by up, before the conversation.save; or
You can pass created_by directly here:

doing it this way, you can remove this save, these both lines:

don’t require you to call save after.

1 Like

@leandrodesouzadev dude thank you so much, i can’t believe i didn’t notice that i was setting one object but saving another obkect, actually it was supposed to be

conversation_message.created_by = request.user

and not

conversation.created_by = request.user

all this while i’m thinking why is it null, when i’m obviously saving it.
Once again man, thank you very much

1 Like