Answer the question
In order to leave comments, you need to log in
NOT NULL constraint failed: chat_message.chat_id?
I made a form for messages between users (similar to my own working form for comments). And for some reason this error comes out. There are enough links for such an error, but none of the suggestions helped me. I also tried to delete and reinstall the database with migrations - nothing. Prescribed in the chat field nall=True, blank = True, everything is also past.
My model (here, by the way, I will be grateful if someone throws at least something about how to correctly write logic for chats)
class Chat(models.Model):
DIALOG = 'D'
CHAT = 'C'
CHAT_TYPE_CHOICES = (
(DIALOG, 'Dialog'),
(CHAT, 'Chat')
)
type = models.CharField( 'Тип',max_length=1,choices=CHAT_TYPE_CHOICES,default=DIALOG )
slug = models.SlugField(unique=True)
def get_absolute_url(self):
return reverse('private_chat_url', kwargs={'slug': self.slug })
class Message(models.Model):
chat = models.ForeignKey(Chat, verbose_name="Чат", on_delete=models.CASCADE)
author = models.ForeignKey(User, verbose_name="Отправитель", on_delete=models.CASCADE)
recipient = models.ForeignKey(User, related_name='received_messages',
verbose_name="Получатель", on_delete=models.CASCADE, default=0)
message = models.TextField("Сообщение")
pub_date = models.DateTimeField('Дата сообщения', default=timezone.now)
is_readed = models.BooleanField('Прочитано', default=False)
def private_chat(request, slug):
pr_chat = get_list_or_404(Chat, slug__iexact=slug)
body_chat = Message.objects.order_by('pk')
if request.method == 'POST':
message_form = MessageForm(request.POST)
if message_form.is_valid():
message_form.instance.author = request.user
message_form.instance.post = pr_chat
message_form.save()
return redirect(pr_chat)
else:
HttpResponseNotFound("<h2>Введены неверные данные</h2>")
else:
message_form = MessageForm()
return render(request, 'chat/private_chat.html', {'pr_chat': pr_chat,
'body_chat': body_chat,
'message_form': message_form,
})
class MessageForm(forms.ModelForm):
message = forms.CharField()
class Meta:
model = Message
fields = ('message',)
<form method="post">
{% csrf_token %}
{{ message_form }}
<button type="submit" style="margin-top:1%; margin-bottom:1%; width:215px;" class="btn btn-outline-primary">Добавить</button>
</form>
Answer the question
In order to leave comments, you need to log in
message_form.instance.post = pr_chat
where is the post model field?
Did you write exactly nall=True in the model field or null =True? Only the last one is true. After changing the model, you need to generate a migration and roll it.
python manage.py makemigrations
python manage.py migrate
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question