Django FileField – 如何将文件保存到不同目录

huangapple go评论76阅读模式
英文:

Django FileField - how to save files to different directories

问题

我有两个类似的上传文件表单但我想根据表单将文件保存在不同的目录中

让我举个例子

如果用户从 Form_1 上传文件 -> 文件应该保存在 ```media/folder_file_1/file.csv```

如果用户从 Form_2 上传文件 -> 文件应该保存在 ```media/folder_file_2/file.csv```

关于 ```models.py, forms.py, views.py, urls.py```,我只是在 Django 文档中使用了示例

**index.html:**
```html
<!DOCTYPE html>
{% load static %}

<body>
<div class="page_secondblock secondblock">
    <div class="secondblock__container _container">
        <h1 class="secondblock__title">
            The file you want to update:   
        </h1>
        <h2 class="secondblock__title">
            The file from which you want to get information:
        </h2>
    </div>
</div>
<div class="page_thirdblock thirdblock">
    <div class="thirdblock__container _container">
        <form method="POST" enctype="multipart/form-data" class="upload1" id="upload_container"> 
            {% csrf_token %}
            {{form.as_p}}
            <input type="submit" value="Submit">
        </form>
        <form method="POST" enctype="multipart/form-data" class="upload2" id="upload_container">
            {% csrf_token %}
            {{form.as_p}}
            <input type="submit" value="Submit">
        </form>
    </div>
</div>
</body>

models.py:

from django.db import models

class UploadFile(models.Model):
    file = models.FileField(upload_to='working/')

forms.py:

from django import forms  
from .models import UploadFile

class UploadFileForm(forms.ModelForm):
    class Meta:
        model = UploadFile
        fields = ['file']

views.py:

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect 
from .forms import UploadFileForm
  
def index(request):
    return render(request, "index.html")
 
def tools(request):
    return render(request, "index.html")
 
def login(request):
    return render(request, "index.html")

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('home')    
    else:
        form = UploadFileForm()
        context = {
            'form':form,
        }
    return render(request, 'index.html', context)

urls.py:

from django.contrib import admin
from django.urls import path, re_path
from actualization import views

urlpatterns = [
    re_path(r'^tools', views.tools, name='tools'),
    re_path(r'^login', views.login, name='login'),
    path('get_result/', views.get_result),
    path('home/', views.upload_file, name='upload_file'),
]
英文:

I have two similar forms for upload files, but I want to save files in different directories depending on the form.

Let me explain, for example:

if User uploaded file from Form_1 -> file should be save in media/folder_file_1/file.csv

if User uploaded file from Form_2 -> file should be save in media/folder_file_2/file.csv

Regarding models.py, forms.py, views.py, urls.py I just used examples from Django docs.

index.html:

&lt;!DOCTYPE html&gt;
{% load static %}

&lt;body&gt;
&lt;div class=&quot;page_secondblock secondblock&quot;&gt;
    &lt;div class=&quot;secondblock__container _container&quot;&gt;
        &lt;h1 class=&quot;secondblock__title&quot;&gt;
            The file you want to update:   
        &lt;/h1&gt;
        &lt;h2 class=&quot;secondblock__title&quot;&gt;
            The file from which you want to get information:
        &lt;/h2&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;page_thirdblock thirdblock&quot;&gt;
    &lt;div class=&quot;thirdblock__container _container&quot;&gt;
        &lt;form method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot; class=&quot;upload1&quot; id=&quot;upload_container&quot;&gt; 
            {% csrf_token %}
            {{form.as_p}}
            &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
        &lt;/form&gt;
        &lt;form method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot; class=&quot;upload2&quot; id=&quot;upload_container&quot;&gt;
            {% csrf_token %}
            {{form.as_p}}
            &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
        &lt;/form&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;

models.py:

from django.db import models

class UploadFile(models.Model):
    file = models.FileField(upload_to=&#39;working/&#39;)

forms.py:

from django import forms  
from .models import UploadFile

class UploadFileForm(forms.ModelForm):
    class Meta:
        model = UploadFile
        fields = [&#39;file&#39;]

views.py:

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect 
from .forms import UploadFileForm
  
def index(request):
    return render(request, &quot;index.html&quot;)
 
def tools(request):
    return render(request, &quot;index.html&quot;)
 
def login(request):
    return render(request, &quot;index.html&quot;)

def upload_file(request):
    if request.method == &#39;POST&#39;:
        form = UploadFileForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(&#39;home&#39;)    
    else:
        form = UploadFileForm()
        context = {
            &#39;form&#39;:form,
        }
    return render(request, &#39;index.html&#39;, context)

urls.py:

from django.contrib import admin
from django.urls import path, re_path
from actualization import views

urlpatterns = [
    re_path(r&#39;^tools&#39;, views.tools, name=&#39;tools&#39;),
    re_path(r&#39;^login&#39;, views.login, name=&#39;login&#39;),
    path(&#39;get_result/&#39;, views.get_result),
    path(&#39;home/&#39;, views.upload_file, name=&#39;upload_file&#39;),
]

答案1

得分: 1

好的,我会翻译代码部分:

from django.db import models

def _upload_location(instance, filename):
    return f&#39;{instance.owner.username}/{filename}&#39;


class UploadFile(models.Model):
    file = models.FileField(upload_to=_upload_location)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

这样它会将文件存储在您在settings.py中分配的文件夹中作为MEDIA_ROOT。然后将其放入与您的用户名相同名称的文件夹中。然后是文件名。

英文:

Ok, so the way I do it is the following:

from django.db import models

def _upload_location(instance, filename):
    return f&#39;{instance.owner.username}/{filename}&#39;


class UploadFile(models.Model):
    file = models.FileField(upload_to=_upload_location)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

This way it stores the file inside of the folder you assigned in your settings.py as MEDIA_ROOT. Then puts it in a folder with the same name as your username. Afterwards follows the filename.

If the username as a foldername is a good choice is for sure debatable but you get the idea.

Find another good example here: FileField.upload_to

huangapple
  • 本文由 发表于 2023年6月29日 15:16:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定