我可以成功上传文件,但我无法将该文件夹说明为已登录的用户名。我尝试过以下方法:
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class Document(models.Model):
user = models.OneToOneField(User)
document = models.ImageField(upload_to=user_directory_path)
uploaded_at = models.DateTimeField(auto_now_add=True)
但收到以下错误:
Django Version: 1.9.6
Exception Type: RelatedObjectDoesNotExist
Exception Value: Document has no user.
表格如下:
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('document', )
观点如下:
@login_required
def profile(request, extra_context={}):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('profile')
else:
form = DocumentForm()
return render(request, 'meta/profile.html', {
'form': form
})
任何建议都会受到赞赏,Alan。
以下全文:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/profile/
Django Version: 1.9.6
Python Version: 2.7.10
Installed Applications:
('django.contrib.auth',
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.humanize',
'avatar',
'mathfilters',
'smart_selects',
'tinymce',
'dbbackup',
'django_ical',
'crispy_forms',
'meta')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'fbf.middleware.QueryCountDebugMiddleware')
Traceback:
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/Users/alantingey/freebetfriend.com/meta/views.py" in profile
71. form.save()
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/forms/models.py" in save
451. self.instance.save()
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/base.py" in save
708. force_update=force_update, update_fields=update_fields)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/base.py" in save_base
736. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
820. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
859. using=using, raw=raw)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/query.py" in _insert
1039. return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
1059. for sql, params in self.as_sql():
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in as_sql
1019. for obj in self.query.objs
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in pre_save_val
968. return field.pre_save(obj, add=True)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/fields/files.py" in pre_save
311. file.save(file.name, file, save=False)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/fields/files.py" in save
90. name = self.field.generate_filename(self.instance, name)
File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/fields/files.py" in generate_filename
328. directory_name, filename = os.path.split(self.upload_to(instance, filename))
File "/Users/alantingey/freebetfriend.com/meta/models.py" in user_directory_path
22. today_date = datetime.datetime.today().date()
Exception Type: AttributeError at /profile/
Exception Value: type object 'datetime.datetime' has no attribute 'datetime'
答案 0 :(得分:1)
好像你有
from datetime import datetime
所以你的命令应该是
today_date = datetime.today().date()
或者只是将您的import
声明更新为
import datetime
答案 1 :(得分:1)
您没有在任何地方收集登录用户!您的表单仅收集文档字段。
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('document', )
以下代码失败是很自然的
return 'user_{0}/{1}'.format(instance.user.id, filename)
要修复它,请将视图更改为
obj = form.save(commit=False)
obj.user = request.user
obj.save()