这就是我得到的
IntegrityError at /malex/upload/
NOT NULL constraint failed: malex_document.uploaded_by_id
Request Method: POST
Request URL: http://127.0.0.1:8000/malex/upload/
Django Version: 2.0.5
Exception Type: IntegrityError
模型
class Profile(models.Model):
username = models.OneToOneField(User, on_delete=models.CASCADE)
password = models.TextField(max_length=80,blank=True)
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
uploaded_by = models.ForeignKey(Profile,on_delete=models.CASCADE)
date_uploaded = models.DateTimeField(auto_now_add=True)
表格
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
观看次数
def upload(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
**newdoc.uploaded_by = request.user.profile**
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('upload'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render(request,'upload.html',{'documents': documents, 'form': form})
如果我添加此行,则仅凭单行行者的建议
'AnonymousUser' object has no attribute 'profile'
此完整性错误甚至使事情更奇怪的是文件已上传
~/nup/malex/media/documents/2018/06/22$ ls -lh 262_V01_C06_R000_TEy_BH_131072H.ats
-rw------- 1 milenko milenko 46M јун 22 07:22 262_V01_C06_R000_TEy_BH_131072H.ats
为什么会出现此错误以及如何解决?
答案 0 :(得分:1)
您没有设置uploaded_by
属性。由于它不能为空,因此会引发错误。要解决此问题,您需要像这样保存之前向新的Document实例提供uploaded_by
:
@login_required
def upload(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.uploaded_by = request.user.profile # if Profile has onetofield with User model
# newdoc.uploaded_by = request.user if Profile is your user_model
newdoc.save()
注意uose login_required装饰器,以确保当前用户已通过身份验证。
您还可以将uploaded_by
设置为可空字段:
uploaded_by = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
在这种情况下,uploaded_by
不是必需的,并且对于新记录将设置为ULL。