我正在尝试从内置的User模型内置的django中保存当前登录用户的用户名。
model.py
class Notes(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE)
note = models.CharField(max_length = 100000000)
def __str__(self):
return self.note
views.py
@login_required
def saveNote(request):
if request.method == 'POST':
note = request.POST['note']
print(request.user.username)
note = Notes(username=request.user.username ,note = request.POST["note"])
note.save()
return redirect('/')
但这显示了一个错误。 我想将当前用户与注释一起保存在Notes表中。 我应该怎么做?
答案 0 :(得分:1)
您的代码中几乎没有错误。
首先
username = models.ForeignKey(User, on_delete=models.CASCADE)
应该是
user = models.ForeignKey(User, on_delete=models.CASCADE)
和
note = models.CharField(max_length = 100000000) charfield can hold 255 char
所以你需要
note = models.TextField()
@login_required
def saveNote(request):
if request.method == 'POST':
note = request.POST['note']
print(request.user.username)
note = Notes(username=request.user #user=request.user if you change your model field name
,note = note)
note.save()
return redirect('/')