简体   繁体   English

Django:文件上传与文件创建(上传不起作用)

[英]Django: File Uploading vs File Creating (upload not working)

I have two forms: one where you create a new object (then it creates a new empty file for it), and one where you create an object with an existing file (it uploads the file).我有两种形式:一种是创建新对象(然后为它创建一个新的空文件),另一种是使用现有文件创建对象(它上传文件)。 The creation form works just fine, it takes the name of the new created object and creates a file with the same name and uploads it in the static folder.创建表单工作正常,它采用新创建的对象的名称并创建一个同名文件并将其上传到静态文件夹中。 However, the second form, it tells you that it got the file object and everything, but the file is not found anywhere.但是,第二种形式,它告诉您它获得了文件对象和所有内容,但在任何地方都找不到该文件。

I tried to change directories and modify code and everything and it doesn't seem to work at all and I do not know where is the issue, here are my codes:我试图更改目录并修改代码以及所有内容,但它似乎根本不起作用,我不知道问题出在哪里,这是我的代码:

views.py:视图.py:

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

def upload(request):
    print request.POST
    structure = Structure(name=request.POST['name'], file=request.POST['file'])
    structure.save()
    return redirect('/structures')

models.py:模型.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

html template: html模板:

[...]
<!--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>
<!--END-CREATE-->

<!--UPLOAD-->
<div class="col-md-12">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">Mettre en ligne une nouvelle structure</h3>
        </div>
        <div class="panel-body">
        <form class="form-horizontal" action="/upload", method="post">
        {% csrf_token %}
          <fieldset>
            <div class="form-group">
              <label for="name" class="col-lg-6 control-label">Structure</label>
              <div class="col-lg-6">
                <input type="text" name="name" id="name"> 
                <label for="structures"></label>
              </div>
            </div>
            <div class="form-group">
              <label for="file" class="col-lg-6 control-label">Fichier de la structure</label>
              <div class="col-lg-6">
                <input type="file" name="file" id="file">
              </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>
<!--END-UPLOAD-->
[...]

urls.py:网址.py:

url(r'^create$', views.create),
url(r'^upload$', views.upload),

settings.py:设置.py:

STATIC_URL = '/static/'
MEDIA_ROOT = 'files/'

Here is the server log when uploading a file:这是上传文件时的服务器日志:

I appreciate the help guys.我感谢帮助家伙。

<QueryDict: {u'csrfmiddlewaretoken': [u'D8Cz7fUkxbpl2hYb3lmjnzm85jzlMjti'], u'name': [u'doctor list'], u'file': [u'doctors1.ods']}>
[01/Nov/2017 10:10:13]"POST /upload HTTP/1.1" 302 0
[01/Nov/2017 10:10:13]"GET /structures HTTP/1.1" 301 0
[01/Nov/2017 10:10:13]"GET /structures/ HTTP/1.1" 200 8195

By the way: in the html template I show the file path of each object, when I create the object and thus create a new file, the path is shown like this structures/file.ext but when I upload it, it only displays it like this: files.ext顺便说一句:在html模板中,我显示了每个对象的文件路径,当我创建对象并因此创建一个新文件时,路径显示如下structures/file.ext但是当我上传它时,它只显示它像这样: files.ext

Well there is few things you should change:好吧,您应该更改几件事:

1- Using forms to handle uploading: 1- 使用表单处理上传:

in your forms.py :在你的forms.py

class FileUpload(forms.ModelForm):
    class Meta:
        model = Structure
        fields = ('file', 'name')

in your views.py :在您的views.py

form = FileUpload(request.POST, request.FILES)
if form.is_valid():
    form.save()
    # you can also do some other stuff before saving the form.

2- Adding enctype to your form: 2- 将enctype添加到您的表单中:

Change this:改变这个:

<form class="form-horizontal" action="/upload", method="post">

to :到 :

<form class="form-horizontal" action="/upload", method="post" enctype="multipart/form-data">

This should solve your problem.这应该可以解决您的问题。

And for last part: You're using forms to upload a file.最后一部分:您正在使用表单上传文件。 so if your file name already exist in upload folder, form will add some random words and numbers to end of the file.所以如果你的文件名已经存在于上传文件夹中,表单会在文件末尾添加一些随机的单词和数字。 so you can't show the file path like that, it might be wrong.所以你不能像那样显示文件路径,它可能是错误的。 you can make an instance of uploaded file and get the name or path.您可以制作上传文件的实例并获取名称或路径。

it would be something like this:它会是这样的:

file = form.save()
# You can get the file url like this:
print(file.file.url)
# Or file path:
print(file.file.path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM