I want to create a new file with the same name as the object I am creating. I want to create a new "structure object" with the name str in the database and at the same time a new file called str in the designated uploading folder. When I do that I get an AttributeError of 'file' object has no attribute '_committed'
Here are my codes:
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),
template:
<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>
The code was working just fine until I added the file creating lines in the views.py
And this is a screenshot of the error I am getting:
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'
Edit: I didn't show the full trace of the bug: it tells me that the bug is located when I save the object to the database: structure.save()
I think, you need to pass a File
object for the corresponding field of type FileField
upon saving.
From Django docs on saving/retrieving a file:
When you access a FileField on a model, you are given an instance of FieldFile as a proxy for accessing the underlying file. The API of FieldFile mirrors that of File .
FieldFile.save(name, content, save=True)
Note that the content argument should be an instance of django.core.files.File , not Python's built-in file object. You can construct a File from an existing Python file object like this:
from django.core.files import File f = open('/path/to/hello.world') myfile = File(f)
Thus, you might want to try:
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.