1
我有一個Model Formset,它應該將通過POST發送的文件添加到數據庫中。Model Formset覆蓋現有條目而不是添加
但是,表單包含數據庫中已存在的文件的ID,這會導致信息被覆蓋。例如,HTML輸出的形式是這樣的:
<label for="id_files-0-theFile">File:</label>
<input type="file" name="files-0-theFile" id="id_files-0-theFile" />
<input type="hidden" name="files-0-id" value="1" id="id_files-0-id" />
.... and so on, for each entry form 0 .. 10
這第三行 - 的files-0-id
- 是什麼,我相信導致覆蓋,但我不知道如何解決這個問題。我希望系統爲每個提交創建新的File對象,而不是使用現有的ID。
我的模板打印等形式的信息,以便:
<form action=... >
{{ fileform.management_form }}
{% for form in fileform.forms %}
{{ form.as_p }}
{% endfor %}
</form>
和模型,形式和視圖的相關部分:
class File(models.Model):
theFile = models.FileField("File", upload_to='files/%Y/%m/%d')
entry = models.ForeignKey(Entry)
size = models.CharField(blank=True, max_length=100)
name = models.CharField(blank=True, max_length=150)
class FileForm(forms.ModelForm):
class Meta:
model = File
exclude = ('entry', 'size')
def add(request):
FileFormSetFactory = modelformset_factory(File, form=FileForm, extra=8,
exclude=file_forms_excludes,)
file_formset = FileFormSetFactory(prefix='files')
if request.method == 'POST':
file_formset = FileFormSetFactory(request.POST, request.FILES,
prefix='files')
if file_formset.is_valid():
for f in file_formset.save(commit=False):
f.name = f.theFile.name.split("/")[-1]
f.size = convert_bytes(f.theFile.size)
f.entry = entry #primary key to another object, removed for clarity
f.save()
...
return HttpResponseRedirect('/doc/' + str(entry.id))
else:
context = {}
context['fileform'] = file_formset
context['entryform'] = entry_form
context['entities'] = entities()
return render_to_response('add.html', context)