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