我正在尝试将表单数据保存到匿名用户,但是在尝试为eg:here它的消息保存一些数据时出现以下错误。 我不清楚问题是什么?
ValueError:无法在0x03D88350处分配“ SimpleLazyObject:django.contrib.auth.models.AnonymousUser对象>>
模型
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,on_delete=models.CASCADE)
message = models.CharField(max_length=200)
def __unicode__(self):
return self.message
查看
from django.shortcuts import render
from django.contrib.auth import authenticate, logout, login
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from chat_2 import settings
#import time
from .models import Chat
def test(request):
return render(request,'alpha/test.html',{'next': next})
def Login(request):
next = request.GET.get('next', '/home/')
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
#WelcomeUser(user)
return HttpResponseRedirect(next)
else:
return HttpResponse("Account is not active at the moment.")
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "alpha/login.html", {'next': next})
def Logout(request):
#logout(request)
#Chat.objects.all().delete()
return HttpResponseRedirect('/login/')
def Home(request):
c = Chat.objects.all()
return render(request, "alpha/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.')