我正在用 Django 编写聊天应用程序,在替换我的消息后出现错误:
IntegrityError at /chatapp/post/ NOT NULL constraint failed: chatapp_chat.message
这是我的模型.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
这是我的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})
和.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>
我搜索了很多答案,但找不到适合我的问题的解决方案。
请您参考如下方法:
当您发布转换为 None 的空消息(甚至在发布变量中不存在“msgbox”变量)时会发生错误:msg = request.POST.get(' msgbox',无)。我会用空字符串检查来更改此 block :
msg = request.POST.get('msgbox', None)
c = Chat(user=request.user, message=msg)
if msg != '':
c.save()
到:
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
更新:根据您的表单输入名称,将 var name 'msgbox' 更改为 'chat-msg'。
