Django:在views.py中创建一个空文件

时间:2017-10-31 15:57:52

标签: python django

我想创建一个与我正在创建的对象同名的新文件。 我想在数据库中创建一个名为str的新“结构对象”,同时在指定的上传文件夹中创建一个名为str的新文件。当我这样做时,我得到'file' object has no attribute '_committed'的AttributeError 这是我的代码:

views.py:

def create(request):
    print request.POST
    filename = request.POST['name'] 
    f = open(filename, "w")
    structure = Structure(name=request.POST['name'], file=f)
    structure.save()
    return redirect('/structures')

models.py:

class Structure(models.Model):
    name = models.CharField(max_length=120)
    file = models.FileField(upload_to='structures')
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.name

urls.py: url(r'^create$', views.create),

模板:

<div class="col-md-12">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">Créer une nouvelle structure</h3>
        </div>
        <div class="panel-body">
        <form class="form-horizontal" action="/create", method="post">
        {% csrf_token %}
          <fieldset>
            <div class="form-group">
              <label for="name" class="col-lg-6 control-label">Nom de la structure</label>
              <div class="col-lg-6">
                <input type="text" name="name" id="name">
              </div>
            </div>
            <div class="form-group">
              <div class="col-lg-10 col-lg-offset-2" align="center">
                <button type="submit" value="Create" class="btn btn-primary">Créer</button>
              </div>
            </div>
          </fieldset>
        </form>
        </div>
    </div>
</div>

代码工作正常,直到我在views.py

中添加了创建行的文件

这是我得到的错误的屏幕截图:

Environment:


Request Method: POST
Request URL: http://localhost:8000/create

Django Version: 1.8
Python Version: 2.7.13
Installed Applications:
('apps.structure',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "/home/kaiss/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kaiss/Documents/proj/apps/structure/views.py" in create
  27.   structure.save()
File "/home/kaiss/.local/lib/python2.7/site-packages/django/db/models/base.py" in save
  710.                        force_update=force_update, update_fields=update_fields)
File "/home/kaiss/.local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  738.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/kaiss/.local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  822.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/kaiss/.local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  861.                                using=using, raw=raw)
File "/home/kaiss/.local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/kaiss/.local/lib/python2.7/site-packages/django/db/models/query.py" in _insert
  920.         return query.get_compiler(using=using).execute_sql(return_id)
File "/home/kaiss/.local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  962.             for sql, params in self.as_sql():
File "/home/kaiss/.local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in as_sql
  920.                 for obj in self.query.objs
File "/home/kaiss/.local/lib/python2.7/site-packages/django/db/models/fields/files.py" in pre_save
  313.         if file and not file._committed:

Exception Type: AttributeError at /create
Exception Value: 'file' object has no attribute '_committed'

编辑:我没有显示错误的完整痕迹:它告诉我在将对象保存到数据库时找到错误:structure.save()

1 个答案:

答案 0 :(得分:1)

我认为,您需要在保存时为FileField类型的相应字段传递File对象。

Django docs起保存/检索文件:

  

当您访问模型上的 FileField 时,您将获得 FieldFile 的实例作为访问基础文件的代理。 FieldFile 的API反映了文件

的API      

FieldFile.save(name, content, save=True)

     

请注意,content参数应该是 django.core.files.File 的实例,而不是Python的内置文件对象。您可以从现有的Python文件对象构建文件,如下所示:

from django.core.files import File

f = open('/path/to/hello.world')
myfile = File(f) 

因此,您可能想尝试:

from django.core.files import File

def create(request):
    print request.POST
    filename = request.POST['name'] 
    f = open(filename, "w")
    structure = Structure(name=request.POST['name'], file=File(f))
    structure.save()
    return redirect('/structures')