user3599620 user3599620 - 1 month ago 8
Python Question

IntegrityError:NOT NULL constraint failed: chatapp_chat.message

I'm writing chat application in Django and after subbing my message I get error:

IntegrityError at /chatapp/post/ NOT NULL constraint failed: chatapp_chat.message


This is my models.py:

from django.db import models
from django.contrib.auth.models import User

class Chat(models.Model):
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, blank=True, null=True)
message = models.CharField(max_length=200)

def __unicode__(self):
return self.message


This is my view.py

def home(request):
c = Chat.objects.all()
return render(request, "chatapp/home.html", {'home': 'active', 'chat': c})

def post(request):
if request.method == "POST":

msg = request.POST.get('msgbox', None)

c = Chat(user=request.user, message=msg)
if msg != '':
c.save()
return JsonResponse({ 'msg': msg, 'user': c.user.username })
else:
return HttpResponse('Request must be POST.')

def messages(request):
c = Chat.objects.all()
return render(request, 'chatapp/messages.html', {'chat': c})


And .html

<body>

<div class="panel-heading">Chat Box</div>
<div id="msg-list-div" class="panel-body">
<ul id="msg-list" class="list-group">
{% for obj in chat %}
{% if obj.user == request.user %}
<li class="text-right list-group-item">{{ obj.message }}</li>
{% else %}
<li class="text-left list-group-item">{{ obj.message }}</li>
{% endif %}
{% empty %}
<li class="text-right list-group-item">No messages yet!</li>
{% endfor %}
<script>
var chatlist = document.getElementById('msg-list-div');
chatlist.scrollTop = chatlist.scrollHeight;
</script>
</ul>
</div>


<form id="chat-form" method="post" action="/chatapp/post/">
{% csrf_token %}
<div id="chat-bottom" class="input-group">
<input type="text" id="chat-msg" name="chat-msg" class="form-control"/>
<span class="input-group-btn">
<input class="btn btn-default" id="send" type="submit" value="Send"/>
</span>


I've searched through lot of answers but couldn't find the right solution for my problem.

Answer

Erorr occurs than you post empty message (or even 'msgbox' var is absent in post vars) that converts to None in this line: msg = request.POST.get('msgbox', None). I would change this block with empty string check:

    msg = request.POST.get('msgbox', None)
    c = Chat(user=request.user, message=msg)
    if msg != '':
        c.save()

to:

    msg = request.POST.get('msgbox', '').strip()
    if msg:
        c = Chat.objects.create(user=request.user, message=msg)
        return JsonResponse({ 'msg': msg, 'user': c.user.username })
    else:
        return JsonResponse({'some status': 'indicating that empty/no msg posted'})
        # or no return anything

update: and change var name 'msgbox' to 'chat-msg' according to your form input name.

Comments