我想通过Django Forms更新多个文件,并将上传文件的路径保存到数据库表中。但是每当我使用这种方法更新文件数据时,都会将文件数据存储到数据库中,但在数据库表中会为多次上传的每个文件创建不同的行。
我尝试了以下方法
多个文件是通过other_files上传的
forms.py
from django import forms
from categories.models import Categories
from .models import Process
class ProcessingForm(forms.ModelForm):
files = forms.ModelChoiceField(queryset=Categories.objects.all())
class Meta:
model = Process
fields = ('category', 'files', 'lookup_files', 'other_files')
models.py
from django.db import models
class Process(models.Model):
category = models.CharField(max_length=25, choices=CATEGORIES, null=True,
blank=True)
files = models.CharField(max_length=50, null=True, blank=True)
lookup_files = models.FileField(upload_to='processing/%Y/%m/%d/Lookup',
verbose_name=('Lookup File [For Tagging]'), validators=
[validate_file_extension])
other_files =models.FileField(upload_to='processing/%Y/%m/%d/other_files',
null=True, blank=True)
views.py
from django.shortcuts import render, redirect
from categories.models import Categories
from django.contrib import messages
from .models import Process
def process(request):
if request.method == 'POST':
form = ProcessingForm(request.POST, request.FILES)
# print(form)
if form.is_valid():
category = form.cleaned_data['category']
files = form.cleaned_data['files']
lookup_files = request.FILES['lookup_files']
other_files = request.FILES.getlist('other_files')
print(len(other_files))
# file_list = []
for oth in other_files:
print(oth)
# file_list.append(oth)
form = Process(category=category, files=files,
lookup_files=lookup_files, other_files=oth)
form.save()
messages.success(request, 'File uploaded succcessfully')
return redirect('process')
else:
print("Form is not valid")
messages.warning(request, 'File extension is not valid')
return redirect('process')
else:
form = ProcessingForm()
return render(request, 'process/process.html', {'form':form})
答案 0 :(得分:0)
您应该更改策略(这是最好的方法,恕我直言)。您仅需要一个用于存储文件以及进程表和文件表之间关系的表。为此使用ForeignKey关系。您将拥有一个进程和许多文件(OneToMany)。
class OtherFile(models.Model):
other_file = models.FileField(upload_to='processing/%Y/%m/%d/Lookup', verbose_name=('Lookup File [For Tagging]'), validators=[validate_file_extension])
process = models.ForeignKey(to=Process, on_delete=models.PROTECT) # this is process_id
答案 1 :(得分:0)
如果您不想使用外键,请使用任何分隔符(如 '---' AllLinks = [oth,]
)连接文件名,您可以将其保存在一行中。当您必须获取数据时,您必须使用 AllLinks.split('---')
再次拆分名称以获取文件链接。
为了避免这种情况,最好建立外键关系。