我正在制作一个简单的应用程序,用于对用户进行身份验证并允许他们上传文件。我有一个问题,当我尝试将用户作为外键添加到数据库的模型时,出现此错误:
'User' object has no attribute '_committed'
models.py
fs = FileSystemStorage(location='/media/uploads')
class FileInstance(models.Model):
file = models.FileField(storage=fs)
owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
views.py
def upload_file(request):
if request.method == 'POST':
file = FileInstance(request.FILES['file'], request.user)
file.save()
else:
form = UploadFileForm()
return render(request, 'upload.html')
upload.html
{% extends 'commons/base.html' %}
{% block title %} Dodaj plik {% endblock %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
{% endblock %}
堆栈跟踪:
Internal Server Error: /storage/upload/
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jch/PycharmProjects/2019Z_PAMIW_git_gr4/pamw2/storage/views.py", line 36, in upload_file
file.save()
File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 848, in _save_table
for f in non_pks]
File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 848, in <listcomp>
for f in non_pks]
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/files.py", line 286, in pre_save
if file and not file._committed:
File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 257, in inner
return func(self._wrapped, *args)
AttributeError: 'User' object has no attribute '_committed'
为什么会出现此错误,如何解决呢?我的数据模型是否正确,如果不正确,该如何更改?
修改后
models.py
class FileInstanceForm(ModelForm):
class Meta:
model = FileInstance
fields = ['file']
views.py
def upload_file(request):
if request.method == 'POST':
form = FileInstanceForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('files.html')
else:
form = FileInstanceForm()
return render(request, 'upload.html', {form: form})
upload.html
<form action="." method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload"/>
我的表格显示不正确。我没有办法附加文件,并且html无法渲染。就是这样: